我有一个名为 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不包含lifestyle_attributes,即使我在传记模型中接受了accepts_nested_attributes_for语句,并且还在模型中定义了传记和生活方式之间的关联?我还在强参数允许列表中添加了lifestyle_attributes。
但是,如果我在 Rails 控制台中运行此命令,则分配确实有效:
b = Biography.first
b.update("lifestyle_attributes"=>{"diet"=>"2", "smoke"=>"false", "drink"=>"2"})
最佳答案
require
和permit
实际上是ActionController::Parameters
的方法。 require
(在本例中为 :biography
)需要出现在您从主干 View 发送的哈希中。
require 方法确保存在特定参数,如果未提供,则 require 方法会引发错误。它返回一个 ActionController::Parameters
的实例,用于传递给 require 的键,即 :biography
。
关于ruby-on-rails - 为什么这个 Rails 嵌套属性分配不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349796/