首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >以嵌套形式更新many_to_many关联

以嵌套形式更新many_to_many关联
EN

Stack Overflow用户
提问于 2018-09-06 02:44:19
回答 1查看 43关注 0票数 0

对于这个问题,我有三种模式。并使用wicked gem进行多步注册。

用户

代码语言:javascript
运行
复制
class User < ApplicationRecord
  has_one :profile
  has_many :specialties, through: :profile

  accepts_nested_attributes_for :profile, allow_destroy: true
end

配置文件

代码语言:javascript
运行
复制
class Profile < ApplicationRecord
  belongs_to :user
  has_many :profile_specialties
  has_many :specialties, through: :profile_specialties
end

专业

代码语言:javascript
运行
复制
class Specialty < ApplicationRecord
  has_many :profile_specialties
  has_many :profiles, through: :profile_specialties
end

以我的形式,我传递specialty_ids

代码语言:javascript
运行
复制
<%= 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

代码语言:javascript
运行
复制
def update
  @user = current_user
  @user.update_attributes(user_params)
  render_wizard @user
end

我相信rails通过命名来处理关联的更新。但也许我弄错了,需要显式地更新控制器中的关联。或者也许我没有正确命名物品..。

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

更新

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

我有强参数定义为这样

代码语言:javascript
运行
复制
def user_params
  params.permit profile_attributes: [..., :specialty_ids]
end

更新2

这是完整的日志

代码语言:javascript
运行
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-06 04:00:35

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

代码语言:javascript
运行
复制
def user_params
  params.permit profile_attributes: [..., specialty_ids: []]
end
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52195766

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档