【问题标题】:Update many_to_many association in nested form以嵌套形式更新 many_to_many 关联
【发布时间】:2018-09-06 02:44:19
【问题描述】:

我为这个问题的上下文提供了三个模型。并使用wicked gem 进行多步注册。

用户

class User < ApplicationRecord
  has_one :profile
  has_many :specialties, through: :profile

  accepts_nested_attributes_for :profile, allow_destroy: true
end

简介

class Profile < ApplicationRecord
  belongs_to :user
  has_many :profile_specialties
  has_many :specialties, through: :profile_specialties
end

专业

class Specialty < ApplicationRecord
  has_many :profile_specialties
  has_many :profiles, through: :profile_specialties
end

在我的表单中,我通过specialty_ids

<%= simple_form_for @user, url: wizard_path do |f| %>

  ...

  <%= simple_fields_for :profile_attributes do |cf| %>

    <%= cf.input :specialty_ids, collection: Role.order(:name), as: :grouped_select, group_method: :specialties, input_html: {multiple: true} %>

  <% end %>

  ...

<% end %>

AfterSignup#update

def update
  @user = current_user
  @user.update_attributes(user_params)
  render_wizard @user
end

我相信 Rails 通过命名来处理关联的更新。但也许我弄错了,需要明确更新控制器中的关联。或者也许我没有正确命名项目......

不管怎样,我有点不清楚为什么个人资料专业不更新。

更新

当我尝试进行更新时,控制台会记录 Unpermitted parameters: :specialty_ids

我有这样定义的强大参数

def user_params
  params.permit profile_attributes: [..., :specialty_ids]
end

更新 2

这是完整的日志

Processing by AfterSignupController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"...", "profile_attributes"=>{"specialty_ids"=>["", "22"], "commit"=>"Save and Continue", "id"=>"step_one"}
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 52], ["LIMIT", 1]]
Unpermitted parameters: :specialty_ids
Unpermitted parameters: :utf8, :_method, :authenticity_token, :commit, :id
   (0.2ms)  BEGIN
  Profile Load (0.2ms)  SELECT  "profiles".* FROM "profiles" WHERE "profiles"."user_id" = $1 LIMIT $2  [["user_id", 52], ["LIMIT", 1]]
  SQL (0.4ms)  DELETE FROM "profiles" WHERE "profiles"."id" = $1  [["id", 110]]
  SQL (0.4ms)  INSERT INTO "profiles" ("user_id", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id"  [["user_id", 52], ["created_at", "2018-09-06 02:30:57.882173"], ["updated_at", "2018-09-06 02:30:57.882173"]]
   (0.5ms)  COMMIT
   (0.2ms)  BEGIN
   (0.2ms)  COMMIT
Redirected to http://localhost:3000/after_signup/requirements

【问题讨论】:

  • 整个控制台消息是什么,里面有重要信息。您尝试传递的参数在控制台中看起来像什么? params 是否需要一个 ID 数组?
  • @Beartech 我已添加完整消息
  • params[:speciality_ids] 是一个数组。试试params.permit profile_attributes: [..., specialty_ids: []]

标签: ruby-on-rails ruby ruby-on-rails-5 simple-form wicked-gem


【解决方案1】:

您的强大参数需要一个数组,因此您需要:

def user_params
  params.permit profile_attributes: [..., specialty_ids: []]
end

【讨论】:

  • 啊,就是这样。比我预期的要简单得多。
  • 参数有时会很痛苦。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 2021-04-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多