0

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.

The comments table

The states table

Could you enlighten me on this? The image below what happens when I remove the 'belongs_to :previous_state, class_name: "State"'.

No method error when removing the belongs_to statement

Sookie J
  • 823
  • 2
  • 8
  • 16
  • 1
    Are you settings reference for previous_state_id to table states? – Duyet Nguyen Dec 07 '16 at 04:41
  • Yes, Would you look at the post again? I updated it adding an image of the states table. – Sookie J Dec 07 '16 at 04:48
  • 1
    what happens if you remove ```belongs_to :previous_state, class_name: "State"``` ? – Duyet Nguyen Dec 07 '16 at 04:51
  • As you can see in the states table, I am trying to make the comments table reference to the states table. – Sookie J Dec 07 '16 at 04:52
  • What happens when removing it, NoMethodError occurs. I added the error image on the post. – Sookie J Dec 07 '16 at 04:55
  • 1
    Yes, correctly. The problem at that. ```self.previous_state = ticket.state``` Because you have a reference from comment to state via previous_state_id. It means when you call self.previous_state, you must be set the relationship for comment and previous_state – Duyet Nguyen Dec 07 '16 at 04:58
  • Thank you sir. But what does it mean exactly to call `self.previous_state`? What I assume now is that the column `previous_state_id` is already in the comments table, so I thought calling it `self.previous_state` without setting relationship is possible. – Sookie J Dec 07 '16 at 05:06
  • 1
    If you not set relationship, You cant call ```self.previous_state``` but you can call by another way. Maybe: ```State.find(self.previous_state_id)``` – Duyet Nguyen Dec 07 '16 at 06:05
  • It seems `self.previous_state_id = ticket.state` also works. I think rails cleverly takes care of this. You answer helps me a lot. – Sookie J Dec 07 '16 at 06:38

0 Answers0