嵌套属性的 fields_for 不返回任何内容

发布于 2024-10-08 06:26:47 字数 1187 浏览 0 评论 0原文

我正在尝试在 Rails 3.0.3 中创建嵌套模型表单。这是我的模型:

class Bird < ActiveRecord::Base
  has_one :taxon, :as => :organism
  accepts_nested_attributes_for :taxon
end

class Taxon < ActiveRecord::Base
  belongs_to :organism, :polymorphic => true
end

这是控制器方法:

def new
  @bird = Bird.new
  @bird.build_taxon
end

这是表单:

New Bird
<% form_for @bird do |f| %>
<p>
    <%= f.label :wingspan %>
    <%= f.text_field :wingspan %>
</p>
<p>
    <%= f.label :body_length %>
    <%= f.text_field :body_length %>
</p>
<% f.fields_for :taxon do |builder| %>
    <%= builder.label :common_name %>
    <%= builder.text_field :common_name %>
    <%= builder.label :genus_name %>
    <%= builder.text_field :genus_name %>
    <%= builder.label :species_name %>
    <%= builder.text_field :species_name %>
<% end %>
<%= f.submit %>
<% end %>

当我运行新方法时,分类单元的字段不会显示。 html 源代码中没有任何关于它们的提示。我听说如果嵌套模型为零(即如果我忘记在控制器方法中构建它),就会发生这种情况,但它就在那里。我在视图中添加了一些条件代码只是为了确定。

那么,谁让我在这里拍额头呢?我缺少什么?

谢谢!

I'm trying to create a nested model form in Rails 3.0.3. Here are my models:

class Bird < ActiveRecord::Base
  has_one :taxon, :as => :organism
  accepts_nested_attributes_for :taxon
end

class Taxon < ActiveRecord::Base
  belongs_to :organism, :polymorphic => true
end

Here's the controller method:

def new
  @bird = Bird.new
  @bird.build_taxon
end

And here's the form:

New Bird
<% form_for @bird do |f| %>
<p>
    <%= f.label :wingspan %>
    <%= f.text_field :wingspan %>
</p>
<p>
    <%= f.label :body_length %>
    <%= f.text_field :body_length %>
</p>
<% f.fields_for :taxon do |builder| %>
    <%= builder.label :common_name %>
    <%= builder.text_field :common_name %>
    <%= builder.label :genus_name %>
    <%= builder.text_field :genus_name %>
    <%= builder.label :species_name %>
    <%= builder.text_field :species_name %>
<% end %>
<%= f.submit %>
<% end %>

When I run the new method, The fields for taxon don't show up. There's no hint of them in the html source. I've heard that this can happen if the nested model is nil (i.e. if I had forgotten to build it in the controller method), but it's there. I added some conditional code in the view just to make sure.

So, who will make me smack my forehead here? What am I missing?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

小猫一只 2024-10-15 06:26:47

您使用的是 Rails 3 吗?如果是这样,它应该是:

<%= form_for @bird do |f| %>

<%= f.fields_for :taxon do |builder| %>

注意等于。

Are you using Rails 3? If so it should be:

<%= form_for @bird do |f| %>

and

<%= f.fields_for :taxon do |builder| %>

Note the equals.

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