views:

177

answers:

1

I am currently using nested model mass assignment on one of my models. It works a treat, however, I'd like to be able to ensure that any nested models that are created "belong_to" the same user.

I've managed to implement this by using alias method chaining with:

  def contact_attributes_with_user_id=(attributes)
    self.contact_attributes_without_user_id = attributes.merge( "user_id" => user_id )
  end
  alias_method_chain :contact_attributes=, :user_id

Now this works fine, but it means I can no longer have attribute protection on user_id for the contact - which could easily catch someone out in the future.

Can anyone come up with a better way?

A: 

What if you add a before_save hook to your Contact model, like this:

belongs_to :parent
validates_presence_of :parent_id

before_save :assign_user_id

private
def assign_user_id
  self.user_id = parent.user_id
end

This way your Contacts' user_ids will follow the parent model's and you don't have to worry about assigning at all (you can get rid of the alias_method_chain).

Alex Reisner
Great idea. One slight difficulty I can see (and not reflected in the original question) is my contacts have_many :foos, rather than has_one -> belong_to. Although I could easily get it to default to the value of the first foos user_id.
Theozaurus