【问题标题】:Adding empty record for nested attribute in rails为rails中的嵌套属性添加空记录
【发布时间】:2013-12-29 08:15:53
【问题描述】:

我正在使用 Rails 4/Ruby 2.0.0。我有两个模型 - Articles 和 Graphics。 Articleshas_manyGraphics。因此,在我的代码中,我试图将一条空记录添加到文章的图形集合中,以便在表单中会有一组空的字段来添加新记录。我无法弄清楚为什么这些字段没有显示在表单上。

我尝试了多种构建图形集合的方法,但似乎都没有奏效。我肯定错过了一些非常小的东西。

文章.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

图形.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 %>
...

在表单辅助方法中构建它

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

使用 ActiveRecord 回调

文章.rb

...
after_initialize :build_graphics

private

def build_graphics
    self.graphics.build
end

在控制器中构建它

ArticleController.rb

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

【问题讨论】:

  • 在控制器中执行是默认的执行方式。其余的看起来不错。你可能在使用强参数吗?我建议阅读此nofail.de/2013/10/debugging-rails-applications-in-development 并观看此railscasts.com/episodes/196-nested-model-form-revised
  • 感谢您提及强大的参数,我确实忘记将其添加到允许列表中,所以我确信这会导致问题。但不幸的是,这并没有解决问题。我现在会查看这些链接,看看是否有什么发现。
  • 我认为您缺少= 标志:&lt;%= f.fields_for :graphics
  • @Alex ,缺少的 = 正是问题所在。我讨厌这样的问题,我盯着它看了好几个小时。这无济于事,我一直不清楚何时使用,何时不使用。由于我没有要标记的答案,因此显示评论解决了我的问题的标准是什么?
  • 我会为此添加一个答案

标签: ruby-on-rails nested-attributes has-many


【解决方案1】:

问题在于form_for 和fields_for 都需要使用&lt;%=,因为它们会呈现表单的内容。

所以,要解决你的问题,你需要写

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2023-03-28
    • 2012-05-21
    • 1970-01-01
    相关资源
    最近更新 更多