简体   繁体   中英

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

The following is giving me issue:

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

I think it's because I'm calling :reject_if twice, not 100% sure. But when ever I uncomment the photo_title reject_if line my image doesn't get upload if I select one. If I comment the line out then it does.

How can I combine both conditions into one reject_if condition? If that makes sense.

Kind regards

This:

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

is the same as this:

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

The fat-arrow arguments are actually a Hash, the braces are essentially added by Ruby behind your back. A Hash doesn't allow duplicate keys so the second :reject_if value overwrites the first one and you end up with this:

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

You can combine both conditions in one Proc though:

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

You could also use a separate method:

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

Try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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