ruby-on-rails 如何允许数组具有强参数

slhcrj9b  于 2023-10-21  发布在  Ruby
关注(0)|答案(6)|浏览(137)

我有一个运行中的Rails 3应用程序,它使用了has_many:through associations,这并不是,因为我将其改造为Rails 4应用程序,让我在Rails 4版本中从关联模型中保存id。
这三个相关型号的两个版本是相同的。
Categorization.rb

class Categorization < ActiveRecord::Base

  belongs_to :question
  belongs_to :category
end

Question.rb

has_many :categorizations
has_many :categories, through: :categorizations

Category.rb

has_many :categorizations
has_many :questions, through: :categorizations

在这两个应用程序中,类别ID都像这样传递到create操作中

"question"=>{"question_content"=>"How do you spell car?", "question_details"=>"blah ", "category_ids"=>["", "2"],

在Rails3应用程序中,当我创建一个新问题时,它会插入到问题表,然后插入到分类表

SQL (82.1ms)  INSERT INTO "questions" ("accepted_answer_id", "city", "created_at", "details", "province", "province_id", "question", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)  [["accepted_answer_id", nil], ["city", "dd"], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["details", "greyound?"], ["province", nil], ["province_id", 2], ["question", "Whos' the biggest dog in the world"], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["user_id", 53]]
  SQL (0.4ms)  INSERT INTO "categorizations" ("category_id", "created_at", "question_id", "updated_at") VALUES (?, ?, ?, ?)  [["category_id", 2], ["created_at", Tue, 14 May 2013 17:10:25 UTC +00:00], ["question_id", 66], ["updated_at", Tue, 14 May 2013 17:10:25 UTC +00:00]]

在rails4应用程序中,在它处理了RightController #create中的参数之后,我在服务器日志中得到了这个错误

Unpermitted parameters: category_ids

问题只会被插入到问题表中

(0.2ms)  BEGIN
  SQL (67.6ms)  INSERT INTO "questions" ("city", "created_at", "province_id", "question_content", "question_details", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING "id"  [["city", "dd"], ["created_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["province_id", 3], ["question_content", "How's your car?"], ["question_details", "is it runnign"], ["updated_at", Tue, 14 May 2013 17:17:53 UTC +00:00], ["user_id", 12]]
   (31.9ms)  COMMIT

尽管我没有在Questions模型上存储category_ids,但我将category_ids设置为questions_controller中允许的参数

def question_params

      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end

谁能解释一下我应该如何保存category_id?请注意,在这两个应用的categories_controller.rb中都没有创建操作。
这是两个应用程序中相同的三个表

create_table "questions", force: true do |t|
    t.text     "question_details"
    t.string   "question_content"
    t.integer  "user_id"
    t.integer  "accepted_answer_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "province_id"
    t.string   "city"
  end

 create_table "categories", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "categorizations", force: true do |t|
    t.integer  "category_id"
    t.integer  "question_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

更新
这是Rails3应用程序中的创建操作

def create
      @question = Question.new(params[:question])
      respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
end

这是Rails4应用程序中的创建操作

def create
      @question = Question.new(question_params)

       respond_to do |format|
      if @question.save
        format.html { redirect_to @question, notice: 'Question was successfully created.' }
        format.json { render json: @question, status: :created, location: @question }
      else
        format.html { render action: "new" }
        format.json { render json: @question.errors, status: :unprocessable_entity }
      end
    end
    end

这就是question_params方法

private
    def question_params 
      params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids)
    end
4smxwvx5

4smxwvx51#

这个https://github.com/rails/strong_parameters看起来像文档的相关部分:
允许的标量类型有String、Symbol、NilClass、Numeric、TrueClass、FalseClass、Date、Time、DateTime、StringIO、IO、Rack Dispatch::Http::QuarteradedFile和Rack::Test::QuarteradedFile。
要声明params中的值必须是允许的标量值数组,请将键Map到空数组:

params.permit(:id => [])

在我的应用程序中,category_id以数组的形式传递给create操作

"category_ids"=>["", "2"],

因此,在声明强参数时,我显式地将category_ids设置为数组

params.require(:question).permit(:question_details, :question_content, :user_id, :accepted_answer_id, :province_id, :city, :category_ids => [])

现在工作完美!
(**重要:**正如@勒纳特在注解中所指出的,数组声明必须位于属性列表的末尾,否则会出现语法错误。)

6ioyuze2

6ioyuze22#

如果你想允许一个哈希数组(或者从JSON的Angular 来看是an array of objects

params.permit(:foo, array: [:key1, :key2])

这里需要注意两点:

  1. array应该是permit方法的最后一个参数。
    1.你应该在数组中指定哈希的键,否则你会得到一个错误Unpermitted parameter: array,在这种情况下很难调试。
zengzsys

zengzsys3#

数组应该是permit方法的最后一个参数。

params.permit(:id => [])

同样,从Ruby 1.9或更新版本开始,您可以使用:用途:

params.permit(id: [])
aiqt4smr

aiqt4smr4#

如果你有一个这样的哈希结构:

Parameters: {"link"=>{"title"=>"Something", "time_span"=>[{"start"=>"2017-05-06T16:00:00.000Z", "end"=>"2017-05-06T17:00:00.000Z"}]}}

这就是我如何让它工作:

params.require(:link).permit(:title, time_span: [[:start, :end]])
gwo2fgha

gwo2fgha5#

当你想允许多个数组字段时,你必须在允许的同时列出数组字段,如给定的-

params.require(:questions).permit(:question, :user_id, answers: [], selected_answer: [] )

(this作品)

3ks5zfa0

3ks5zfa06#

我还不能发表评论,但以下的同胞陌生人的解决方案,你也可以保持嵌套的情况下,你有关键的价值观是一个数组。就像这样:

filters: [{ name: 'test name', values: ['test value 1', 'test value 2'] }]

这一方法:

params.require(:model).permit(filters: [[:name, values: []]])

相关问题