1

以下是给我的问题:

accepts_nested_attributes_for :photo, 
:reject_if => proc { |attributes| attributes['image'].blank? }, 
:reject_if => proc { |attributes| attributes['photo_title'].blank? },
:allow_destroy => true

我认为这是因为我调用了 :reject_if 两次,而不是 100% 确定。但是,当我取消注释 photo_title reject_if 行时,如果我选择一个,我的图像就不会上传。如果我将这一行注释掉,那么它会这样做。

如何将这两个条件组合成一个 reject_if 条件?如果这是有道理的。

亲切的问候

4

2 回答 2

5

这:

accepts_nested_attributes_for :photo, 
  :reject_if => proc { |attributes| attributes['image'].blank? }, 
  :reject_if => proc { |attributes| attributes['photo_title'].blank? },
  :allow_destroy => true

与此相同:

accepts_nested_attributes_for :photo, {
  :reject_if => proc { |attributes| attributes['image'].blank? }, 
  :reject_if => proc { |attributes| attributes['photo_title'].blank? },
  :allow_destroy => true
}

粗箭头参数实际上是一个哈希,大括号本质上是 Ruby 在你背后添加的。哈希不允许重复键,因此第二个:reject_if值会覆盖第一个值,您最终会得到:

accepts_nested_attributes_for :photo,
  :reject_if => proc { |attributes| attributes['photo_title'].blank? },
  :allow_destroy => true

您可以在一个 Proc 中结合这两个条件:

accepts_nested_attributes_for :photo,
  :reject_if => proc { |attributes| attributes['image'].blank? || attributes['photo_title'].blank? }, 
  :allow_destroy => true

您还可以使用单独的方法:

accepts_nested_attributes_for :photo,
  :reject_if => :not_all_there,
  :allow_destroy => true

def not_all_there(attributes)
  attributes['image'].blank? || attributes['photo_title'].blank?
end
于 2012-05-12T16:24:29.503 回答
1

试试这个

accepts_nested_attributes_for :photo, 
 :reject_if => proc { |attributes| attributes['image'].blank? || attributes['photo_title'].blank?}, 
 :allow_destroy => true
于 2012-05-12T12:23:10.650 回答