Rails模式accepted_nested_attributes_for正常工作

时间:2011-10-21 18:26:18

标签: ruby-on-rails

我有这样的模特:

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

当我填写表单中的地址,并将表单发布到BusinessesController的create操作时,日志显示参数是正确的:

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

在BusinessesController的create操作中

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

我检查日志,发现@business.save没有向数据库插入任何有关locaitons的信息,但只有关于业务的信息,但是params[:business]显然包含了hash的位置,所以我在哪里错了?

1 个答案:

答案 0 :(得分:1)

我猜它出错的地方是reject_if检查,

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

您在位置表中的位置属性在哪里?据我了解,你应该检查以下方式

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