Rails own_to 和单表继承行为不正常
我有一个 Bike
模型和一个 Component
模型。几个模型继承自 Component
:Frame
、Chain
、Crankset
等。
当我提交表单时,我的参数看起来像这样:
"bike" => { "frame" => { "id" => "4" }, "chain" => { "id" => "19" }, ... }
在我的控制器中,以下代码中断:
@bike = Bike.new(params[:bike])
> Frame(#90986230) expected, got HashWithIndifferentAccess(#81888970)
如果我破解表单以生成以下参数,它会起作用:
"bike" => { "frame_id" => "4", "chain_id" => "19" ... }
这是我的模型:
class Bike < ActiveRecord::Base
belongs_to :frame
belongs_to :chain
...
end
class Component < ActiveRecord::Base
has_many :bikes
end
class Frame < Component
end
单表继承正在工作 - 我可以调用 Frame.first
并Component.all
没有问题。
我要疯了吗?嵌套参数不是通常的约定吗?这就是产生的:
- f.fields_for @bike.frame do |frame|
= frame.hidden_field :id
我做错了什么?
I have a Bike
model and a Component
model. Several models inherit from Component
: Frame
, Chain
, Crankset
etc.
When I submit my form, my params look like this:
"bike" => { "frame" => { "id" => "4" }, "chain" => { "id" => "19" }, ... }
In my controller, the following code breaks:
@bike = Bike.new(params[:bike])
> Frame(#90986230) expected, got HashWithIndifferentAccess(#81888970)
If I hack my form to generate the following params, it works:
"bike" => { "frame_id" => "4", "chain_id" => "19" ... }
Here's my models:
class Bike < ActiveRecord::Base
belongs_to :frame
belongs_to :chain
...
end
class Component < ActiveRecord::Base
has_many :bikes
end
class Frame < Component
end
Single table inheritance is working - I can call Frame.first
and Component.all
without issue.
Am I going insane? Isn't the nested params the usual convention? That's what gets generated by:
- f.fields_for @bike.frame do |frame|
= frame.hidden_field :id
What am I doing wrong??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在使用嵌套表单,因此如果您使用
accepts_nested_attributes_for
标记,则嵌套参数应该有效(请参阅railscast 196/197)。You are using nested forms, so nested params should work if you use the
accepts_nested_attributes_for
tag (see railscast 196/197).