I’m reading a book (Rails 3 in Action) that’s building a project management system which has Projects, and then Tickets associated with projects, and users can make Comments on tickets, and when they make a Comment, they can also indicate the State (new, finished etc) of the Ticket.
The users select the state of the Ticket while submitting a Comment form, and this State has to somehow also be reflected on the Ticket.rb model, so after the form is submitted, the author uses a callback
after_create :set_ticket_state
in the Comment class that will also put the state on the Ticket object
My question relates to the code in this callback method. I understand why he write
self.state
with “self” referring to the comment class, but I don’t understand why he uses
self.ticket.state
if he’s trying to update the Ticket object, as “self” would still refer to Comment class.
I’m guessing that he can do it this way because of the association
belongs_to :ticket
but that’s just a guess and I’d like some more explanation if possible.
class Comment < ActiveRecord::Base
after_create :set_ticket_state
belongs_to :ticket
belongs_to :user
belongs_to :state
validates :text, :presence => true
delegate :project, :to => :ticket
private
def set_ticket_state
self.ticket.state = self.state
self.ticket.save!
end
end
The state that the comment belongs to and the state that the ticket belongs to are two separate objects, or rows in the database. The point of that line of code is to reference the state of the ticket, and update the state it accordingly. If you just use
self.statethen you will just be changing the state of the comment.