简体   繁体   中英

Adding empty record for nested attribute in rails

I'm working in Rails 4/Ruby 2.0.0. I have a two models - Articles and Graphics . Articles has_many Graphics . So, in my code I am trying to add an empty record to the graphics collection on the article so that in the form, there will be an empty set of fields to let a new record be added. I cannot figure out why the fields do not show up on the form though.

I've tried multiple methods of building the graphics collection but none seem to do the trick. Surely I must be missing something insanely small.

Article.rb

class Article < ActiveRecord::Base
    has_many :graphics, :dependent => :destroy, :foreign_key => 'article_id' 

    accepts_nested_attributes_for :graphics,
      :allow_destroy => true,
      :reject_if     => :all_blank
end

Graphic.rb

class Graphic < ActiveRecord::Base
    belongs_to :article
    validates_presence_of :path, :caption
end

_form.html.erb

...
<% f.fields_for :graphics do |g| %>
    <div class="clear clearfix pad-b-20">
        <div class="w-1-2 left f-left">
          <div class="field">
            <%= g.label :path %><br>
            <%= g.text_field :path %>
          </div>
        </div>
        <div class="w-1-2 left f-left">
          <div class="field">
            <%= g.label :caption %><br>
            <%= g.text_field :caption %>
          </div>
        </div>
    </div>
<% end %>
...

Building it in a form helper method

articles/_form.html.erb

<%= form_for(setup_article(@article)) do |f| %>

form_helper.rb

module FormHelper
    def setup_article(article)
        article.graphics.build
        article
    end  
end

Using an ActiveRecord callback

Article.rb

...
after_initialize :build_graphics

private

def build_graphics
    self.graphics.build
end

Building it in the controller

ArticleController.rb

...
def new
    @article = Article.new
    @article.graphics.build
end
...

The problem is that both for form_for and for fields_for you need to use <%= , because they render the contents of the form.

So, to solve your problem, you need to write

...
<%= f.fields_for :graphics do |g| %>
   Your content
<% end %>
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM