Question

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?

Was it helpful?

Solution

Try doing:

def create_bar
  bar = Bar.build(... other params ...)
  bar.user_id = user_id
  bar.save!
end

OTHER TIPS

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

attr_protected filters the attributes in the attributes= method wich is called in new. You can solve your problem with:

def create_bar
  returning Bar.new( other attributes ) do |bar|
    bar.user_id = user_id
    bar.save!
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top