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

标签 ruby-on-rails ruby

我有一个名为 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"})

最佳答案

requirepermit实际上是ActionController::Parameters的方法。 require(在本例中为 :biography)需要出现在您从主干 View 发送的哈希中。

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

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

相关文章:

ruby - 在 rspec 中定义 `after` 别名的正确方法是什么?

ruby - 写一个原子操作

ruby-on-rails - 英雄数据库 :pull not working

ruby - 将转义的 XML 实体转换回 UTF-8

ruby-on-rails - Rails 4 + 枚举 : How to upcase the values in a collection_select?

ruby-on-rails - 如何在 Rails 4.2 中添加 JSON 文件导出功能

ruby-on-rails - 我通过 Rails 模型调用 "undefined method",但通过 Rails 控制台调用时效果很好

ruby-on-rails - 如何获取具有 min has_many 记录的记录(加入数据)

ruby-on-rails - 使用 Apple 登录 : verify token at server side

ruby-on-rails - 如何让专家政策更干?