如何允许数组具有强参数

2024-04-04

我有一个功能正常的 Rails 3 应用程序,它使用 has_many :through 关联,但它不是,因为我将其重新制作为 Rails 4 应用程序,让我可以保存 Rails 4 版本中关联模型的 id。

这三个相关模型对于两个版本来说是相同的。

分类.rb

class Categorization < ActiveRecord::Base

  belongs_to :question
  belongs_to :category
end

问题.rb

has_many :categorizations
has_many :categories, through: :categorizations

类别.rb

has_many :categorizations
has_many :questions, through: :categorizations

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

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

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

 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]]

在 Rails 4 应用程序中,在处理 QuestionController#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

虽然我没有将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_ids?请注意,这两个应用程序的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

Update

这是 Rails 3 应用程序的创建操作

  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

这是 Rails 4 应用程序的创建操作

   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

This https://github.com/rails/strong_parameters https://github.com/rails/strong_parameters似乎是文档的相关部分:

允许的标量类型为 String、Symbol、NilClass、Numeric、TrueClass、FalseClass、Date、Time、DateTime、StringIO、IO、 ActionDispatch::Http::UploadedFile 和 Rack::Test::UploadedFile。

要声明 params 中的值必须是允许的标量值的数组,请将键映射到空数组:

params.permit(:id => [])

在我的应用程序中,category_ids 以数组形式传递给创建操作

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

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

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

现在完美运行!

(重要的:正如 @Lenart 在评论中指出的那样,数组声明必须是在最后属性列表的,否则你会得到语法错误。)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何允许数组具有强参数 的相关文章

  • 指向特征矩阵的指针数组

    我在代码中使用 Eigen 的 MatrixXd 矩阵 在某个时刻我需要一个 3D 矩阵 由于 Eigen 没有三维矩阵类型 因为它仅针对线性代数进行了优化 因此我创建了一个 MatrixXd 类型的指针数组 Eigen MatrixXd
  • 来自索引范围 Swift 的新数组

    我怎样才能做这样的事情 从数组中取出前 n 个元素 newNumbers numbers 0 n 目前出现以下错误 error could not find an overload for subscript that accepts th
  • Rubymine 6 更新/刷新 Rails 项目中可用的方法和路径?

    这是一个例子 假设我更新路线resources foo这给我带来了一些新的道路 例如 new foo session当我开始在 ERB 视图中输入路径时 我希望它向我显示 建议自动完成与路径匹配的名称 当我输入 new foo 我会得到所有
  • 目前最流行的 Ruby on Rails AUTHORIZATION gem/plugin 是什么? [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • 遵循 http://ruby.railstutorial.org/ 教程时出现 RSpec 错误

    我到处搜索但似乎找不到解决方案 我一直在关注有关的教程http ruby railstutorial org http ruby railstutorial org 我在第 3 章中尝试使用 rspec spec 执行测试 但是我不断收到以
  • 如何使用 Perl 分割文本文件并将其存储到二维数组中?

    230215 01 16 2000 57533 0 1045403 0 0 217623 230215 01 18 2000 77659 0 1045403 0 0 217624 230215 01 25 2000 76583 0 1045
  • Rails 4:资产未在生产中加载

    我正在尝试将我的应用程序投入生产 但图像和 CSS 资源路径不起作用 这是我目前正在做的事情 图像资源位于 app assets images image jpg 样式表位于 app assets stylesheets style css
  • 如何从一维数组和静态字符串创建对象

    我想要一个像 var obj ABC name true dob true CDE name true dob true EFG name true dob true CBA name true dob true XYZ name true
  • 对象数组的数组(二维数组)JNI

    我正在努力创建自定义对象类型 ShareStruct 的二维数组 jobjectArray ret jobjectArray ins jobjectArray outs jclass myClass env gt FindClass env
  • 我在 Rails 中使用了保留字吗?

    这是我的模型 class Record lt ActiveRecord Base belongs to user belongs to directory end class Directory lt ActiveRecord Base h
  • 浏览器关闭时 Omniauth 会话过期

    在我的 Rails 3 应用程序中 我使用 Omniauth 进行用户身份验证部分 fb twitter 实际上我遵循这个 https github com RailsApps rails3 mongoid omniauth https g
  • Rails:named_scope、lambda 和块

    我认为以下两个是等效的 named scope admin lambda company id conditions gt company id company id named scope admin lambda do company
  • 用数组或向量实现多维数组

    我想使用单个数组或向量实现多维数组 可以像通常的多维数组一样访问它 例如 a 1 2 3 我陷入困境的是如何实施 操作员 如果数组的维数为 1 则 a 1 应该返回位于索引 1 处的元素 但是如果维数大于一怎么办 对于嵌套向量 例如 3 维
  • F# 中的数组初始化

    如何根据给定的记录类型在 F 中创建和初始化数组 假设我想创建一个包含 100 个 record1 记录的数组 e g type record1 value1 string value2 string let myArray Array i
  • 高效创建抗锯齿圆形蒙版

    我正在尝试创建抗锯齿 加权而不是布尔 圆形掩模 以制作用于卷积的圆形内核 radius 3 no of pixels to be 1 on either side of the center pixel shall be decimal a
  • 来自控制器的 Rails 验证

    有一个联系页面 可以输入姓名 电话 电子邮件和消息 然后发送到管理员的电子邮件 没有理由将消息存储在数据库中 问题 如何 在控制器中使用 Rails 验证 根本不使用模型 或者 在模型中使用验证 但没有任何数据库关系 UPD Model c
  • 将数组拆分为特定数量的块

    我知道array chunk 允许将数组拆分为多个块 但块的数量根据元素的数量而变化 我需要的是始终将数组拆分为特定数量的数组 例如 4 个数组 以下代码将数组分为 3 个块 两个块各有 2 个元素 1 个块有 1 个元素 我想要的是将数组
  • 资产管道:仅对一个控制器使用 javascript 文件

    在 Ruby on Rails v4 中 我希望仅为特定控制器加载一个 js 文件 或一组 js 文件 执行此操作的标准方法是什么 在 application js 中有 require tree 线 我假设这需要删除 所以我并不总是加载每
  • 将rails_admin 与rails_api 结合使用

    我最初将此发布为Rails api GitHub 上的问题 https github com sferik rails admin issues 2617 但由于不活跃 我现在将其发布在这里 我正在尝试使用rails admin使用 Rai
  • 如何使用 std::array 模拟 C 数组初始化“int arr[] = { e1, e2, e3, ... }”行为?

    注意 这个问题是关于不必指定元素数量并且仍然允许直接初始化嵌套类型 这个问题 https stackoverflow com questions 6111565 now that we have stdarray what uses are

随机推荐