简体   繁体   English

Rails:通过表单中的对象 ID 数组进行 has_many 关联

[英]Rails: has_many association through array of object IDs from form

I have a model Group which has_many Users .我有一个模型Group has_many Users

class Group < ApplicationRecord
  belongs_to :user
  has_many :users
  serialize :user_ids, Array
end

I'm using JS on the front end to add User ids to an array user_ids .我在前端使用 JS 将User ID 添加到数组user_ids The hidden field looks as such:隐藏字段如下所示:

 = f.hidden_field :user_ids, id: "ids_field"

After selecting a few users, adding them to a JS array and assiginging the value of the hidden field to t hat array,I submit using strong params (with user_ids as an array) to create a new object from the params:选择几个用户后,将它们添加到 JS 数组并将隐藏字段的值分配给 t hat 数组,我提交使用强参数(以 user_ids 作为数组)从参数创建一个新对象:

@group = Group.new(group_params)

def group_params
  params.require(:group).permit(:name, :user_id, :user_ids=>[])
end

The log shows a commit with the user_ids in a comma-delimited list:日志在逗号分隔列表中显示带有 user_ids 的提交:

Processing by GroupsController#create as JS

Parameters: {"utf8"=>"✓", "group"=>{"name"=>"", "user_ids"=>["25,1"]}, "commit"=>"Save Squad"}

Inspecting the Group in the console shows that only the first ID in the array gets assigned to the Group.在控制台中检查Group显示只有数组中的第一个 ID被分配给组。

irb(main):128:0> Group.last.user_ids
..
[
    [0] 25
]

I've been bashing my head against the wall on this problem for the last two days and simply cannot make it work.在过去的两天里,我一直在用这个问题解决问题,根本无法解决这个问题。 I've tried variations of: - using JSON on the front end - removing serialization on the backend - splitting the array param using.split(",") - playing around with the group_params, including / excluding "=>[]" on user_ids and adding explicit name to my hidden field.我尝试了以下变体: - 在前端使用 JSON - 在后端删除序列化 - 使用 .split(",") 拆分数组参数 - 使用 group_params,包括/排除“=>[]” user_ids 并将显式名称添加到我的隐藏字段。 Often I would get an un-permitted parameters error here.我经常会在这里遇到一个 un-permitted parameters 错误。 - Assigning the array to the group model using Group.users <<.... - 使用 Group.users <<.... 将数组分配给组模型

Any help or direction is greatly appreciated.非常感谢任何帮助或指导。 I feel like I have gotten all parts correct at some point, just not at the same time.我觉得我在某个时候把所有的部分都弄对了,只是不是在同一时间。 If i'm totally off and there is a better way to do this, I'm ready to ditch this and move on.如果我完全离开并且有更好的方法来做到这一点,我准备放弃它并继续前进。

Thank you in advance:)先感谢您:)


Edit : More playing around has shown me that the user_ids array is indeed an array, but only consists of one entry: "25,1".编辑:更多的尝试让我知道 user_ids 数组确实是一个数组,但只包含一个条目:“25,1”。 I solved my problem by taking params[:user_ids][0] and splitting it by comma delimiter, looping through the indices, and saving each one of those users to the group association.我通过采用params[:user_ids][0]并用逗号分隔符将其拆分、遍历索引并将这些用户中的每一个保存到组关联中来解决我的问题。 I don't think this is a great solution and still would like to pass the straight array in without manipulation.我不认为这是一个很好的解决方案,并且仍然希望在不进行操作的情况下传递直数组。

This seems like the classic Has and Belongs to Many situation, as a User can "own" a Group and belong to many Groups.这似乎是经典的 Has and Belongs to Many 情况,因为用户可以“拥有”一个组并属于多个组。 I would do something along the lines of:我会按照以下方式做一些事情:

class Group < ApplicationRecord
  belongs_to :user
  has_many :users_groups
  has_many :users, through: :users_groups
  accepts_nested_attributes_for :users
end

Class User < ApplicationRecord
  belongs_to :group
  has_many :users_groups
  has_many :groups, through: :users_groups
  accepts_nested_attributes_for :groups
end

in your terminal create a migration:在您的终端中创建一个迁移:

rails g migration CreateUsersGroupsJoinTable users groups rails g migration CreateUsersGroupsJoinTable 用户组

This will create a join table with columns:这将创建一个包含列的连接表:

|id|user_ids|group_ids|

This gets you all sorts of Rails methods like:这为您提供了各种 Rails 方法,例如:

u = User.find(1)
 #returns user with ID 1

u.groups
 #will a result of joining Group with UsersGroups ON groups.id = users_groups.group_id WHERE users_groups.user_ids = 1

You can do the reverse too:你也可以反过来:

g = Group.find(1)

g.users
 #returns all user objects that belong to that group.

Then when you are doing forms it gives you things like collection_check_boxes that will automatically build out checkboxes based on things like Group.all or User.all, returning an array that will automatically update the join table and do all of this work it looks like you are doing in JS.然后当你做表单时,它会为你提供诸如collection_check_boxes之类的东西,它会根据 Group.all 或 User.all 之类的东西自动构建复选框,返回一个数组,该数组将自动更新连接表并完成所有这些看起来像你的工作正在用 JS 做。

Though there is an answer, I think the real problem is虽然有答案,但我认为真正的问题是

"user_ids"=>["25,1"]

should be应该

"user_ids"=>["25", "1"]

On the front end I use JS to combine a comma-delimited string like在前端,我使用 JS 来组合一个逗号分隔的字符串,例如

"25,1"

And in the controller I use Ruby to parse it into an array在控制器中,我使用 Ruby 将其解析为数组

params[:user_ids].split(",").uniq

And I can just assign it to the instance.我可以将它分配给实例。 Rails will create associations. Rails 将创建关联。

group.user_ids = params[:user_ids].split(",").uniq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM