Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accepts_nested_attributes_for doesn't work properly for has_one relationship

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.

like image 523
adriandz Avatar asked Mar 03 '10 20:03

adriandz


1 Answers

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))

like image 117
shingara Avatar answered Sep 21 '22 06:09

shingara