Rails own_to 和单表继承行为不正常

发布于 2024-09-25 19:57:11 字数 1023 浏览 4 评论 0原文

我有一个 Bike 模型和一个 Component 模型。几个模型继承自 ComponentFrameChainCrankset 等。

当我提交表单时,我的参数看起来像这样:

"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.firstComponent.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无可置疑 2024-10-02 19:57:11

您正在使用嵌套表单,因此如果您使用 accepts_nested_attributes_for 标记,则嵌套参数应该有效(请参阅railscast 196/197)。

belongs_to :frame
accepts_nested_attributes_for :frame

You are using nested forms, so nested params should work if you use the accepts_nested_attributes_for tag (see railscast 196/197).

belongs_to :frame
accepts_nested_attributes_for :frame
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文