accepts_nested_attributes_for doesn't work properly for has_one relationship

ruby-on-rails

Solution

The has_one build is different of has_many

@purchase.build_sale

See the documentation about has_one http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001834

Account#build_beneficiary (similar to Beneficiary.new("account_id" => id))

Problem

I'm having trouble with accepts_nested_attributes_for in a has_one relationship. The models: Purchase and Sale. ``` class Purchase < ActiveRecord::Base has_one :sale, :dependent => :destroy accepts_nested_attributes_for :sale end class Sale < ActiveRecord::Base belongs_to :purchase end ``` In the controller/new action: ``` @purchase = Purchase.new( :club_id => @club.id, :subcategory_id => subcategory.id ) ``` In the view (HAML): ``` - form_for(@purchase) do |f| # some fields for purchase - f.fields_for :sale do |s| = s.text_field :amount, :size => 6 # and so on ``` PROBLEM: this does not actually render any input boxes for sale in my view. The purchase fields render fine, but the sale fields do not appear. If I add this line to the controller: ``` @purchase.sale.build ``` I get this error: undefined method `build' for nil:NilClass To make things weirder, if I change the association type to has_many instead of has_one, thus creating: ``` class Purchase < ActiveRecord::Base has_many :sales, :dependent => :destroy accepts_nested_attributes_for :sales end ``` Everything starts working just fine - the sale fields start appearing in my view, @purchase.sales.build does not return an error, and so on. Of course, this doesn't really help me, since it's supposed to be has_many, not has_one.

Original source