Lon*_*Guy 1 ruby ruby-on-rails 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
Run Code Online (Sandbox Code Playgroud)
我想这是因为我打电话: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
Run Code Online (Sandbox Code Playgroud)
与此相同:
accepts_nested_attributes_for :photo, {
:reject_if => proc { |attributes| attributes['image'].blank? },
:reject_if => proc { |attributes| attributes['photo_title'].blank? },
:allow_destroy => true
}
Run Code Online (Sandbox Code Playgroud)
胖箭的参数实际上是一个哈希,大括号基本上是由Ruby背后添加的.Hash不允许重复键,所以第二个:reject_if值会覆盖第一个,最后你会得到:
accepts_nested_attributes_for :photo,
:reject_if => proc { |attributes| attributes['photo_title'].blank? },
:allow_destroy => true
Run Code Online (Sandbox Code Playgroud)
您可以将一个条件组合在一个Proc中:
accepts_nested_attributes_for :photo,
:reject_if => proc { |attributes| attributes['image'].blank? || attributes['photo_title'].blank? },
:allow_destroy => true
Run Code Online (Sandbox Code Playgroud)
您还可以使用单独的方法:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
428 次 |
| 最近记录: |