【问题标题】:Permitting params with custom keys允许使用自定义键的参数
【发布时间】:2016-11-08 15:54:34
【问题描述】:

我有一个模型名称 TeamInvite,我正在尝试为其创建一个 team_invite_params 方法。

当我为表创建迁移时,因为我想跟踪发件人和收件人,我选择了自定义字段名称

sender_id

recipient_id

不要混淆哪个用户是哪个用户。

无论如何,当我尝试允许 team_invite 的参数时,我无法告诉 permit 方法,

编辑:

"team_invite"=>{"user"=>"2"}

实际上应该是 recipient_id 下的内容。我尝试过的所有方法要么不起作用,要么最终根本没有传递任何值。

控制器

def create
  @team_invite = TeamInvite.new(team_invite_params)
end 

型号

  class TeamInvite < ApplicationRecord
    belongs_to :recipient, class_name: "User"
    belongs_to :sender, class_name: "User"
  end

参数:

{"utf8"=>"✓", "authenticity_token"=>"0QLA9YiTu9nAf6QJLX5rg0DWa7CAMjqGOlUBICbcL8Ucs2DsCDgGBnhiDXPa/ot8DK0xwTR1D7MASu4/9tVj0w==", "team_invite"=>{"recipient_id"=>"2"}, "commit"=>"Save Team invite"}

查看(如果重要):

<%= form_for :team_invite, url: team_invites_path do |f| %>
  <%= f.select :recipient_id, User.all.collect { |p| [ p.name, p.id ] }, include_blank: false %>
  <%= f.submit %>
<% end %>

迁移:

class CreateTeamInvite < ActiveRecord::Migration[5.0]
  def change
    create_table :team_invites do |t|
      t.references :team, foreign_key: true
      t.integer :recipient_id
      t.integer :sender_id
      t.timestamps
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails model


    【解决方案1】:

    你需要:

    params.permit(:team_invites => [ :user ]) #or whatever other nested team_invite params you want to pass in.
    

    strong_params 的文档:https://github.com/rails/strong_parameters

    【讨论】:

    • 但是我需要将它专门分配给“user_id”,因为还有其他字段也需要被允许。
    • 您可以在控制器操作中执行此操作,例如@team_invite.user_id = params[:team_invite][:user]
    • 我试过了,但收件人 ID 仍然为空。
    • 在这种情况下需要更多代码。您可以发布您的控制器操作以及与请求一起发送的参数表单吗?
    • 已更新。我可以破解我的解决方案,但我真的很感兴趣如何正确地做到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 2014-12-21
    • 1970-01-01
    • 2020-10-30
    相关资源
    最近更新 更多