有没有办法在不允许一切的情况下允许参数中的“未定义”哈希?

时间:2013-10-13 13:36:54

标签: ruby-on-rails-4 params

我有一个模型,在数据库中将名为current_values的Hash序列化为JSON。该模型如下所示:

class Template
  belongs_to :user
  serialize :current_values, JSON
  # has attributes title and description
  # ...
end

现在我想创建一个新模板,控制器如下所示:

class TemplateController < ApplicationController
  # ...
  def create
    template = Template.new(template_params)
    template.save
    # ...
  end

  private

  def template_params
    params.require(:template).permit(:title,
                                     :description,
                                     :current_values)
  end
  # ...
end

如果我将此代码与params一起使用,如下所示:

"template" => {
  "title" => "title",
  "description" => "description",
  "current_values" => {
    "foo" => "foo",
    "bar" => "bar"
  }
}

我收到此错误消息:

Unpermitted parameters: current_values

我已经在http://api.rubyonrails.org/上阅读了permit的文档,但我无法弄清楚如何在不允许current_values的所有内容的情况下允许permit!的任何值。我不知道current_values中有哪些属性,因此我无法传递具有允许属性的数组。并且我不想允许所有内容,因为有人可能会覆盖:user_id

1 个答案:

答案 0 :(得分:0)

要解决此问题,您必须更改方法:

def template_params
  params.require(:template).permit(:title,
                                   :description,
                                   :current_values)
end

为:

def template_params
  params.require(:template).permit(:title,
                                   :description).tap do |whitelisted|
    whitelisted[:current_values] = params[:template][:current_values]
  end
end