Why is the identifier of the association object not populated?

In my Rails application, I have two models: Estimate and Client , which are related to belongs_to State (as in the US).

If I create a simple hash, for example:

 properties = {:state => State.first} 

... I can create a client in the Rails console as follows:

 c = Client.new(properties) 

... and it appears with state_id 1 , as expected.

However , if I try to do this with Estimate, for example:

 e = Estimate.new(properties) 

... it never sets state_id , so I cannot save the association.

The tables for Estimate and Client have the same state_id columns ( int 11 ). The connection is the same. The State object is the same.

What could be the reason for this difference?

Update

This problem was attr_accessible , as Misha pointed out. Another sign that we found was that Estimate.state = State.first returned NoMethodError: undefined method state=

+4
source share
1 answer

Have you attr_accessible in your Estimate model? If so, state may not be available and can only be set as follows:

 e = Estimate.new e.state = State.first 

Update

Note that state= is an instance method, not a class method.

This one does not work :

 Estimate.state = State.first 

This one works :

 e = Estimate.new e.state = State.first 
+2
source

All Articles