如何在ruby / rails中将多个参数传递给Proc?

时间:2012-05-12 12:20:28

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

以下是给我一个问题:

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条件?如果这是有道理的。

亲切的问候

2 个答案:

答案 0 :(得分: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
}

fat-arrow参数实际上是一个Hash,大括号基本上是由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

答案 1 :(得分:1)

试试这个

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