1

オブジェクトをインスタンス化するときに、同じユーザー ID を持つ別のオブジェクトも作成するモデルがあります。

class Foo > ActiveRecord::Base

after_create: create_bar

private

def create_bar
  Bar.create(:user_id => user_id #and other attributes)
end

end

Bar.rb には、ハッカーから保護するために attr_protected があります。

class Bar > ActiveRecord::Base
  attr_protected :user_id, :created_at, :updated_at
end

現状では、attr_protected を無効にするか、Bar オブジェクトの user_id を空白にしない限り、新しい Bar オブジェクトを作成することはできないようです...

attr_protected からの保護を失うことなく、bar オブジェクトが foo から :user_id 属性を受け入れるようにするにはどうすればよいですか?

4

3 に答える 3

10

newcreate、またはfind_or_create_by(および最終的に を呼び出す他のもの) を呼び出すときnewは、追加のオプション . を渡すことができますwithout_protection: true

http://api.rubyonrails.org/v3.2.22/classes/ActiveRecord/Base.html#method-c-new

于 2013-02-28T23:29:09.393 に答える
2

やってみてください:

def create_bar
  bar = Bar.build(... other params ...)
  bar.user_id = user_id
  bar.save!
end
于 2010-01-22T20:58:07.990 に答える
2

attr_protectedattributes=で呼び出されるメソッドの属性をフィルタリングしますnew。次の方法で問題を解決できます。

def create_bar
  returning Bar.new( other attributes ) do |bar|
    bar.user_id = user_id
    bar.save!
  end
end
于 2010-01-22T21:01:20.213 に答える