How do I update the object associated with the model object?

I want something like the following:

@user.update_attributes(:name => "Obama", :profile => { :current_location => 'US' })

      

where the user has their profile.

+2


source to share


2 answers


Make it "nested attributes". The documentation says:

Consider a member model that has one Avatar:

  class Member < ActiveRecord::Base
    has_one :avatar
    accepts_nested_attributes_for :avatar
  end

      



...

allows you to update your avatar through a member:

  params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
  member.update_attributes params['member']
  member.avatar.icon # => 'sad'

      

+7


source


As bjelli said, this is the accepts_nested_attributes_for

method you probably want here. It's important to note that this transition to the profile: id attribute allows it to recognize this update that you want to display.



I would recommend reading this nested_attributes.rb comment to understand more :)

+1


source







All Articles