Fields_for嵌套模型Rails 3.2.2

时间:2012-03-26 10:48:35

标签: ruby ruby-on-rails-3 ruby-on-rails-3.1

我的Rails应用程序中有一些嵌套模型。 我有一篇文章帽子有mny属性。

class Article < ActiveRecord::Base
  has_many :properties, :dependent => :destroy
  accepts_nested_attributes_for :properties
end

class Property < ActiveRecord::Base
  belongs_to :article
end

现在我想在我的视图中编辑它,所以我编辑了控制器

  # GET /articles/new
  # GET /articles/new.json
  def new
    @article = Article.new
    3.times { @article.properties.build }

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @article }
    end
  end

还编辑了View和_format.html.erb

 <%= form_for(@article) do |f| %>
  <% if @article.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@article.errors.count, "error") %> prohibited this article from being saved:</h2>

      <ul>
      <% @article.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </div>
  <% f.fields_for :properties do |prop| %>
            <div class="field">
            <%= prop.label :name %><br />
            <%= prop.text_field :name %>
         </div>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

但是没有办法出现。如果我想创建一个新模型,我看不到属性的任何输入字段。

我做错了什么?

1 个答案:

答案 0 :(得分:4)

您在=行中遗漏了fields_for。也就是说,它应该是:

<%= f.fields_for :properties do |prop| %>