简体   繁体   English

在Rails中为嵌套属性添加空记录

[英]Adding empty record for nested attribute in rails

I'm working in Rails 4/Ruby 2.0.0. 我正在使用Rails 4 / Ruby 2.0.0。 I have a two models - Articles and Graphics . 我有两个模型- ArticlesGraphics Articles has_many 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 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 Graphic.rb

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

_form.html.erb _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.html.erb

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

form_helper.rb form_helper.rb

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

Using an ActiveRecord callback 使用ActiveRecord回调

Article.rb Article.rb

...
after_initialize :build_graphics

private

def build_graphics
    self.graphics.build
end

Building it in the controller 在控制器中构建

ArticleController.rb 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. 问题在于,对于form_forfields_for都需要使用<%= ,因为它们会呈现表单的内容。

So, to solve your problem, you need to write 因此,要解决您的问题,您需要编写

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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