In my Rails app, I have two models, Estimate and Client, which both have a belongs_to relationship to State (as in U.S. states).
If I create a simple hash like this:
properties = {:state => State.first}
... I can build a Client in the Rails console like this:
c = Client.new(properties)
... and it shows up with a state_id of 1, as expected.
However, if I try the same with an Estimate, like this:
e = Estimate.new(properties)
... it never sets the state_id, so I can't save the association.
The tables for Estimate an开发者_运维知识库d Client have identical state_id columns (int 11). The association is the same. The State object is the same.
What could be causing this difference?
Update
This issue was attr_accessible as Misha pointed out. Another symptom we discovered was that Estimate.state = State.first returned NoMethodError: undefined method state=
Have you set attr_accessible in your Estimate model? If so, state may not be accessible and can only be set like this:
e = Estimate.new
e.state = State.first
Update
Note that state= is an instance method, not a class method.
This does not work:
Estimate.state = State.first
This does work:
e = Estimate.new
e.state = State.first
加载中,请稍侯......
精彩评论