Thursday, October 4, 2012

Rails - The key to create model and nested attribute in one go

The key is to add attr_accessible to the nested attribute
i.e. attr_accessible :[nested_member]_attributes

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

  attr_accessible :avatar_attributes
end

params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
member = Member.create(params[:member])
member.avatar.id # => 2
member.avatar.icon # => 'smiling'


Reference: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.