繁体   English   中英

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

[英]How do I pass more than one argument to Proc in ruby/rails?

以下是给我的问题:

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条件? 如果这样的话。

亲切的问候

这个:

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
}

粗箭头参数实际上是一个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

尝试这个

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM