【问题标题】:Rails 6 - params not passing to insert into dbRails 6 - 参数未传递以插入数据库
【发布时间】:2020-05-18 16:54:35
【问题描述】:

我一直在兜圈子。 参数未传递到数据库中。

=> Rails 6.0.3 应用程序

我的模型和架​​构:

class Role < ApplicationRecord
end
create_table "roles", force: :cascade do |t|
    t.string "role_name"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
end

控制器

def create
    @role = Role.new(params[:role_params])
    @role.save
    redirect_to @role
end

使用私有方法:

private
    def role_params
        params.require(:role).permit(:role_name)
    end

对象已创建,但“role_name”列为空。 日志:

Started POST "/roles" for ::1 at 2020-05-18 18:31:16 +0200
Processing by RolesController#create as HTML
  Parameters: {"authenticity_token"=>"TZR2usGh+M66S1Nky8fhR7esIoAlYfSUImPY58Yck+7OYmHlYa2Px7eXCByg0rA8NJoV++mS8OxTCc+GfWFO0Q==", "role"=>{"role_name"=>"ragarg"}, "commit"=>"Save Role"}
   (0.1ms)  begin transaction
  ↳ app/controllers/roles_controller.rb:17:in `create'
  Role Create (0.6ms)  INSERT INTO "roles" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2020-05-18 16:31:16.064816"], ["updated_at", "2020-05-18 16:31:16.064816"]]
  ↳ app/controllers/roles_controller.rb:17:in `create'
   (12.6ms)  commit transaction
  ↳ app/controllers/roles_controller.rb:17:in `create'
Redirected to http://localhost:3000/roles/14
Completed 302 Found in 36ms (ActiveRecord: 14.1ms | Allocations: 7243)

【问题讨论】:

  • @role = Role.new(params[:role_params]) 应该是 @role = Role.new(role_params) 以便使用强参数
  • @dbugger 谢谢你的帮助,就是这样!!!

标签: ruby-on-rails


【解决方案1】:

我觉得你的create 方法有点不对

def create
  @role = Role.new(role_params)
  @role.save
  redirect_to @role
end

应该有效

【讨论】:

    【解决方案2】:

    改变

    @role = Role.new(params[:role_params])

    @role = Role.new(role_params)

    如果想访问控制器中的参数,您可以使用 params[:role][:role_name]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2011-07-16
      • 1970-01-01
      • 2011-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多