views:

71

answers:

2

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?

+2  A: 

Try doing:

def create_bar
  bar = Bar.build(... other params ...)
  bar.user_id = user_id
  bar.save!
end
jonnii
This works! Thanks jonnii.except that in my case I did bar = user.bar.build(...parameters)
Kenji Crosland
+2  A: 

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
Gaspard Bucher
Ah! I see, as long as you get out of new, it works. That's why the other answer worked for me too.
Kenji Crosland
This version returns the object as in your example, not true/false.
Gaspard Bucher