未使用Rails build_association方法发布嵌套属性

时间:2014-05-17 03:50:51

标签: ruby-on-rails ruby-on-rails-4

正如你在mySQL控制台中看到的那样,belongs_to关联正在工作,但由于某种原因,我无法理解我似乎无法传递我的嵌套变量。正如你所看到的那样,它们存在于POST参数中但不是在我的位置表中获取INSERTED - 只是create_at和updated_at日期。

Started POST "/farms" for 127.0.0.1 at 2014-05-17 13:36:27 +1000
Processing by FarmsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"Itl527HcZtgCyUuu+j9lohYRwjOu2AX5hrM/tAswCOc=",
"farm"=> {"location_attributes"=>{"address"=>"xcvbxcv", "longitude"=>"xcvv",
 "latitude"=>"xcvb"}, "name"=>"xvcb", "website"=>"vxbc"}, 
"commit"=>"Create Farm"}
   (0.1ms)  BEGIN
  SQL (0.2ms)  INSERT INTO `locations` (`created_at`, `updated_at`) VALUES
 ('2014-05-17 03:36:27', '2014-05-17 03:36:27')
  SQL (0.2ms)  INSERT INTO `farms` (`created_at`, `location_id`, `name`, `updated_at`, `website`) VALUES ('2014-05-17 03:36:27', 28, 'xvcb', '2014-05-17 03:36:27', 'vxbc')
   (0.4ms)  COMMIT
Redirected to http://localhost:3000/farms/22
Completed 302 Found in 38ms (ActiveRecord: 5.6ms)

我的白名单看起来像这样

# Never trust parameters from the scary internet, only allow the white list through.
def farm_params
  params.require(:farm).permit(:id, :name, :website, :created_at, :updated_at, :location_id, :location_attributes => [:address, :longitude, :latitude, :id] )

end

我的控制器看起来像这样。

def new
  @farm = Farm.new 
  end


def create


@farm = Farm.new(farm_params)
@farm.build_location

respond_to do |format|
  if @farm.save
    format.html { redirect_to @farm, notice: 'Farm was successfully created.' }
    format.json { render action: 'show', status: :created, location: @farm }
  else
    format.html { render action: 'new' }
    format.json { render json: @farm.errors, status: :unprocessable_entity }
  end
 end
end

可信赖的模特。

class Farm < ActiveRecord::Base
  belongs_to :location
  accepts_nested_attributes_for :location #, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
   after_initialize do
    self.location ||= self.build_location()
  end
end

0 个答案:

没有答案