拒绝_if不工作

时间:2011-09-19 12:04:53

标签: ruby-on-rails-3 model nested-forms

:reject_if我遇到了一些麻烦。我不知道为什么以下代码不起作用。

查看 - _form.html.erb:

<%= f.fields_for :questions do |builder| %>
  <div class="nested-field">
    <%= builder.label :id, "Question" %><br />
    <%= builder.collection_select(:id, Question.all(:order => 'question'), :id, :question, { :prompt => 'Select Question' } ) %>
  </div>
  <div class="nested-field">
    <%= builder.label :test1 %><br />
    <%= builder.text_field :test1 %>
  </div>
  <div class="nested-field">
    <%= builder.label :test2 %><br />
    <%= builder.text_field :test2 %>
  </div>
  <div class="nested-field">
    <%= builder.label :description %><br />
    <%= builder.text_field :description %>
  </div>
  <br /><br /><br />
  <hr />
<% end %>

型号 - questionary.rb:

has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :reject_if => lambda { |a| a[:id].blank? }, :allow_destroy => true

非常感谢!

2 个答案:

答案 0 :(得分:4)

而不是

:reject_if => lambda { |a| a[:id].blank? }

:reject_if => lambda { |a| a['id'].blank? }

(注意字符串'id')并完全遵循API,使用proc

:reject_if => proc { |a| a['id'].blank? }

答案 1 :(得分:1)

我查看了API for accepts_nested_attributes_for,发现那里的文档说明了:

  

:reject_if   允许您指定指向检查是否应为特定属性哈希构建记录的方法的Proc或Symbol。

你试过用proc替换lambda吗?这里的语法似乎很特殊,所以lambda可能会被忽略。