我有一个Rails模型叫做Biography,传记有一种生活方式。为什么这个rails嵌套属性分配不起作用
class Lifestyle < ActiveRecord::Base
belongs_to :biography
end
class Biography < ActiveRecord::Base
has_one :lifestyle, dependent: :destroy
accepts_nested_attributes_for :lifestyle
end
,在我BiographyController我有这样的:
def update_biography
biography = current_user.biography
logger.debug("params are: #{params}")
logger.debug("biography_params are: #{biography_params}")
if biography.update(biography_params)
render :json => biography
else
render :json => { :errors => biography.errors.full_messages }, :status => 400
end
end
def biography_params
params.require(:biography).permit(
:disability, :hiv_positive, :blood_type,
lifestyle_attributes: [:id, :diet, :smoke, :drink])
end
这是我从上面我的两个logger.debug语句得到:
params are: {"lifestyle_attributes"=>{"diet"=>"2", "smoke"=>"false", "drink"=>"2"}, "disability"=>"false", "hiv_positive"=>"false", "blood_type"=>"3", "controller"=>"biographies", "action"=>"update_biography", "id"=>"4", "biography"=>{"disability"=>"false", "hiv_positive"=>"false", "blood_type"=>"3"}}
biography_params are: {"disability"=>"false", "hiv_positive"=>"false", "blood_type"=>"3"}
这是为什么我biography_params尽管我已在传记模型中使用了accepted_nested_attributes_for statment,并且还定义了模型中传记与生活方式之间的关联,但不包含lifestyle_attributes?我还在强大的参数许可列表中添加了lifestyle_attributes。
但是,如果我在轨运行这个控制台分配不工作:
b = Biography.first
b.update("lifestyle_attributes"=>{"diet"=>"2", "smoke"=>"false", "drink"=>"2"})
你的参数应该是'params = {“biography”=> {“first_name”=>“new”,“last_name”=>“user”,“lifestyle_attributes”=> {“diet”=>“2” “smoke”=>“false”,“drink”=>“2”}}' –
张贴您的表格为 –
我没有表格。我正在使用backbone.js视图并发送json请求。这是标题:blood_type:“3” 残疾:“false” hiv_positive:“false” lifestyle_attributes:{diet:“2”,smoke:“false”,drink:“2”} – user1801879