我有一个模型,当它实例化一个对象时,还会创建另一个具有相同用户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对象……
如何让bar对象在不失去attr_protected保护的情况下接受来自foo的:user_id属性?
发布于 2010-01-23 04:58:08
尝试执行以下操作:
def create_bar
bar = Bar.build(... other params ...)
bar.user_id = user_id
bar.save!
end发布于 2013-03-01 07:29:09
在调用new、create或find_or_create_by (以及任何其他最终调用new的函数)时,可以传递一个额外的选项without_protection: true。
http://api.rubyonrails.org/v3.2.22/classes/ActiveRecord/Base.html#method-c-new
发布于 2010-01-23 05:01:20
attr_protected过滤在new中调用的attributes=方法中的属性。您可以通过以下方式解决您的问题:
def create_bar
returning Bar.new( other attributes ) do |bar|
bar.user_id = user_id
bar.save!
end
endhttps://stackoverflow.com/questions/2120381
复制相似问题