我在Rails 4上遇到与嵌套归因和强参数相关的问题。我有一个Property
模型,嵌套了Status
模型,但每个属性只有has_one
状态。问题是,当我添加/更新属性时,属性会更新,但不会更新状态。查看服务器日志,似乎Rails已创建状态模型,但决定仅添加/编辑property_id
(外键),created_at
和updated_at
字段。以下是提出要点的日志:
SQL (0.3ms) INSERT INTO "statuses" ("created_at", "property_id", "updated_at") VALUES (?, ?, ?) [["created_at", Sat, 11 Jan 2014 16:03:21 UTC +00:00], ["property_id", 9], ["updated_at", Sat, 11 Jan 2014 16:03:21 UTC +00:00]]
(1.4ms) commit transaction
注意那里没有未经许可的消息。
我很确定这不是与模型相关的问题,因为我试图在Console中执行相同的操作,property.save
正常工作。这指向了与强参数相关的方向。
有什么想法吗?
这是我的代码: 模型/ property.rb
class Property < ActiveRecord::Base
has_one :status, dependent: :destroy
accepts_nested_attributes_for :status
end
控制器/ properties_controller.rb
def create
@property = Property.new(property_params)
@property.build_status
if @property.save
redirect_to @property, :notice => "Property created successfully."
else
render :action => 'new'
end
end
private
def property_params
params.require(:property).permit(:name,
:address_line1, :address_line2, :address_city, :address_county, :address_postcode,
:structure_Notes,
status_attributes: [:id, :letting_start_date, :process, :comission, :check_in_date, :check_out_date, :notes] )
end
感谢您的阅读! :)
更新
过去到服务器的参数包括数据:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"cotr1JZPxPEKga4QbGiFMrEgM5D+UpAzZxEImW5iJvc=", "property"=>{"name"=>"Test Status Again", "address_line1"=>"", "address_line2"=>"", "address_city"=>"", "address_county"=>"", "address_postcode"=>"", "status_attributes"=>{"letting_start_date"=>"2013-01-01", "process"=>"Promoting", "commission"=>"", "check_in_date"=>"", "check_out_date"=>"", "notes"=>"fgjkhsdfkjgh sfjgh sdfhg lskdg"}}, "commit"=>"Create Property"}
答案 0 :(得分:0)
我想我发现了为什么它不起作用。
如果你看看控制器:
def create
@property = Property.new(property_params)
@property.build_status
if @property.save
redirect_to @property, :notice => "Property created successfully."
else
render :action => 'new'
end
end
在构建状态对象之前,很好地分配了属性值。因此,property
保存时没有分配状态值。
这是新代码:
@property = Property.new
@property.build_status
@property.assign_attributes(property_params)
希望这将有助于未来的人...非常感谢所有见过并试图解决这个问题的人!