Skip to content

Instantly share code, notes, and snippets.

@cheeyeo
Created April 1, 2015 22:24
Show Gist options
  • Save cheeyeo/1eb6abe12874d71edee3 to your computer and use it in GitHub Desktop.
Save cheeyeo/1eb6abe12874d71edee3 to your computer and use it in GitHub Desktop.
accepts_nested_attributes
# http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
# need to specify id for an update:
class Member < ActiveRecord::Base
has_one :avatar
accepts_nested_attributes_for :avatar
end
params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
member = Member.create(params[:member])
member.avatar.id # => 2
member.avatar.icon # => 'smiling'
# need to specify id of child record for an update
params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } }
member.update params[:member]
member.avatar.icon # => 'sad'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment