【问题标题】:accepts_nested_attributes_for ignore blank valuesAccepts_nested_attributes_for 忽略空白值
【发布时间】:2011-02-10 23:08:34
【问题描述】:

我有

class Profile
  has_many :favorite_books, :dependent => :destroy
  has_many :favorite_quotes, :dependent => :destroy

  accepts_nested_attributes_for :favorite_books, :allow_destroy => true
  accepts_nested_attributes_for :favorite_quotes, :allow_destroy => true
end

我有一个动态表单,您可以在其中按“+”添加新的文本区域以创建新的收藏夹。 我想要做的是忽略空白的,我发现在更新控制器中比非嵌套属性更难排序。

我暂时拥有的是在 after_save 回调中删除空记录的黑客行为。忽略这些空白对象的最有效方法是什么?

我不想要验证和错误,只是静默删除/忽略。

【问题讨论】:

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


    【解决方案1】:

    有一个内置的验证:

    :reject_if => lambda { |c| c[:name].blank? },
    

    【讨论】:

    • 很棒的提示apneadiving,谢谢!有了这个,我发现了这个(对于其他阅读者)“您也可以设置一个 :reject_if proc,如果它们未能通过您的标准,则静默忽略任何新记录哈希。例如,前面的示例可以重写为:” - @987654321 @
    • Rails 5 有reject_if: :all_blank。我不知道这是否是最近在 Rails 5 中引入的,或者它是否也适用于旧框架版本。
    • 如果我不想reject怎么办?我想要create/update 个人资料,但没有favorite_quotesfavorite_books。它不允许。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多