gpt4 book ai didi

ruby-on-rails - 为什么这个 Rails 嵌套属性分配不起作用

转载 作者:数据小太阳 更新时间:2023-10-29 08:36:37 25 4
gpt4 key购买 nike

我有一个名为传记的 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,即使我已经在 Biography 模型中声明了 accepts_nested_attributes_for 语句,并且还在模型中定义了 Biography 和 Lifestyle 之间的关联?我还在强参数许可列表中添加了 lifestyle_attributes。

但是,如果我在 Rails 控制台中运行它,分配就会起作用:

b = Biography.first
b.update("lifestyle_attributes"=>{"diet"=>"2", "smoke"=>"false", "drink"=>"2"})

最佳答案

requirepermit其实就是ActionController::Parameters的方法。 require 在这种情况下是 :biography 需要出现在您从主干 View 发送的散列中。

require 方法确保特定参数存在,如果未提供,则 require 方法抛出错误。它返回 ActionController::Parameters 的实例,用于传递给 require 的键,即 :biography

关于ruby-on-rails - 为什么这个 Rails 嵌套属性分配不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34349796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com