为什么我的关联对象 ID 没有被填充?
在我的 Rails 应用程序中,我有两个模型:Estimate
和 Client
,它们都与 State
具有 belongs_to
关系(如美国各州)。
如果我创建一个像这样的简单哈希:
properties = {:state => State.first}
...我可以在 Rails 控制台中构建一个客户端,如下所示:
c = Client.new(properties)
...并且它显示的 state_id
为 1
,正如预期的那样。
但是,如果我尝试对估算进行相同的操作,如下所示:
e = Estimate.new(properties)
...它永远不会设置state_id
,因此我无法保存协会。
Estimate
和 Client
表具有相同的 state_id
列 (int 11
)。协会也是一样的。 State
对象是相同的。
是什么导致了这种差异?
更新
正如 Misha 指出的那样,这个问题是 attr_accessible
。我们发现的另一个症状是 Estimate.state = State.first
返回 NoMethodError: undefined method state=
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
and 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=
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否在
Estimate
模型中设置了attr_accessible
?如果是这样,state
可能无法访问,只能像这样设置:更新
请注意,
state=
是实例方法,而不是类方法。这不起作用:
这起作用:
Have you set
attr_accessible
in yourEstimate
model? If so,state
may not be accessible and can only be set like this:Update
Note that
state=
is an instance method, not a class method.This does not work:
This does work: