Reputation: 3034
I have a model that, when it instantiates an object, also creates another object with the same user id.
class Foo > ActiveRecord::Base
after_create: create_bar
private
def create_bar
Bar.create(:user_id => user_id #and other attributes)
end
end
In Bar.rb I have attr_protected to protect it from hackers.
class Bar > ActiveRecord::Base
attr_protected :user_id, :created_at, :updated_at
end
As it stands now I can't seem to create a new Bar object without either disabling the attr_protected or having the Bar object's user_id go blank...
How can I let the bar object accept the :user_id attribute from foo without losing protection from attr_protected?
Upvotes: 1
Views: 1940
Reputation: 6137
attr_protected
filters the attributes in the attributes=
method wich is called in new
. You can solve your problem with:
def create_bar
Bar.new( other attributes ) do |bar|
bar.user_id = user_id
bar.save!
end
end
Upvotes: 2
Reputation: 7524
When calling new
, create
, or find_or_create_by
(and any others that end up calling new
) you can pass an additional option, without_protection: true
.
http://api.rubyonrails.org/v3.2.22/classes/ActiveRecord/Base.html#method-c-new
Upvotes: 10
Reputation: 28312
Try doing:
def create_bar
bar = Bar.build(... other params ...)
bar.user_id = user_id
bar.save!
end
Upvotes: 2