Question

I am having a hard time extending an existing model to include two references to a single table.

My current model is called Order and I need two references (payment_state and delivery_state) to the State table.

It is my understanding that I should run the following command:

rails g migration AddStatesToOrder payment_state:references delivery_state:references

However, the following line comes up in my schema.rb after running rake db:migrate:

# Could not dump table "orders" because of following NoMethodError
#   undefined method `[]' for nil:NilClass

Any help would be greatly appreciated. Thanks!

Was it helpful?

Solution

You should do like this:

rails g migration AddStatesToOrder payment_state_id:integer delivery_state_id:integer

And define the relation like this in the model:

belongs_to :payment_state, class_name: State.model_name
belongs_to :delivery_state, class_name: State.model_name

Why using :integer instead of :references? Because the thing you want to do is not "conventional", it is a customized double-relation to the same model, and Rails cannot guess it for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top