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 を 2 回呼び出しているためだと思いますが、100% 確実ではありません。しかし、photo_title reject_if 行のコメントを外すたびに、画像を選択しても画像がアップロードされません。行をコメントアウトすると、コメントアウトされます。

両方の条件を 1 つの 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 によって背後で追加されます。ハッシュは重複キーを許可しないため、2 番目の:reject_if値が最初の値を上書きし、次のようになります。

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

ただし、両方の条件を 1 つの 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 に答える