Rn2dy
Rn2dy

Reputation: 4190

Rails mode accepts_nested_attributes_for working properly

I have models like this:

class User < ActiveRecord::Base
  has_one :business
end
class Business < ActiveRecord::Base
  belongs_to :user
  has_many : locations
  accepts_nested_attributes_for :locations, :reject_if => lambda { |a| a[:location].blank?} 
  atr_accessible :name, :locations_attributes
  ...
end

class Location < ActiveRecord::Base
  belongs_to :business
  ...
end

when I fill in the address in the form, and post form to the create action of BusinessesController, the log show that the parameters are correct:

... 
"business"=>{"name"=>"sos","locations_attributes"=>{"0"=>{"address"=>"location1"}, "1"=>{"address"=>"location2"}}}
...

In the create action of BusinessesController

# :Post /usres/1/businesses
def create
  @user = User.find(params[:user_id])
  @business = @user.build_business(params[:business])
  if @business.save 
    ...
  else
    ...
  end
end

I check the log and found that @business.save did not insert any information about the locaitons to the database, but only the information about business, but the params[:business] clearly contains the locations hash, so where I was wrong??

Upvotes: 1

Views: 170

Answers (1)

nkm
nkm

Reputation: 5914

I guess where it goes wrong is in the reject_if check,

accepts_nested_attributes_for :locations, 
   :reject_if => lambda { |a| a[:location].blank?}

Where do you have location attribute in locations table? As i understand you should check in the following way

accepts_nested_attributes_for :locations, 
   :reject_if => lambda { |a| a[:address].blank?}

Upvotes: 1

Related Questions