Now I am teaching myself with the book "Rails 4 in action", and got stuck at some point. Let me describe my problem.
I have 3 models that are a state, a ticket and a comment. Both the ticket and the comment belong to the state. The comment belongs to the ticket, and the ticket has many comments. Then here is the comment model class below.
class Comment < ApplicationRecord
belongs_to :ticket
belongs_to :author, class_name: "User"
belongs_to :state
belongs_to :previous_state, class_name: "State"
before_create :set_previous_state
after_create :set_ticket_state
private
def set_previous_state
self.previous_state = ticket.state
end
def set_ticket_state
ticket.state = state
ticket.save!
end
end
What I don't understand is why the following belongs_to statement is needed here.
belongs_to :previous_state, class_name: "State"
The column previous_state_id is already in the comments table, so I am assuming the code 'self.previous_state = ticket.state' in the set_previous_state method can be used without the above belongs_to statement.
Could you enlighten me on this? The image below what happens when I remove the 'belongs_to :previous_state, class_name: "State"'.