Search code examples
ruby-on-railsruby-on-rails-3activerecord

bypass attr_accessible/protected in rails


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?


Solution

  • Try doing:

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