【发布时间】:2017-02-28 13:13:18
【问题描述】:
我正在尝试在具有多个用户的 SNS 应用中创建一个组。 通过 Groups_users 将 has_many 用户分组。
这里我有一个创建组的表单,我想同时将成员(Groups_users)添加到组中。 我在创建组的同时成功地将一个成员添加到组中,但是我无法将多个成员添加到组中。
这是我的代码:
型号:
group.rb
class Group < ApplicationRecord
validates :name, presence: true, uniqueness: true
validates :owner_user_id, presence: true
has_many :groups_users, inverse_of: :group
has_many :users, through: :groups_users
accepts_nested_attributes_for :groups_users
has_many :group_posts
end
groups_user.rb
class GroupsUser < ApplicationRecord
belongs_to :group, inverse_of: :groups_users
belongs_to :user
validates :group, presence: true
validates :user_id, presence: true
end
控制器:
groups_controller.rb
module Users
module Users
class GroupsController < BaseController
def index
@group = Group.new
@group.groups_users.build
@groups = Group.all
end
def create
group = Group.new(group_params)
if group.save!
redirect_to users_groups_path, notice: 'a new group created!'
else
redirect_to users_groups_path, notice: 'The selected group name has already been taken.'
end
end
private
def group_params
params.require(:group).permit(:name, :owner_user_id, groups_users_attributes: [:user_id])
end
end
end
end
观看次数:
groups/index.html.slim
= form_for [:users, @group] do |f|
.field
= f.label :name, 'group name:'
= f.text_field :name, size: 15, maxlength: 20
= f.hidden_field :owner_user_id, value: current_user.id
.field
= f.fields_for :groups_users do |g|
= g.label :user_id, 'user name you want to add'
= g.select :user_id, options_for_select(current_user.mutual_followers.map { |user| [user.name, user.id] }), { }, { multiple: true }
.actions
= f.submit
注意:
- 如果我从视图文件中删除 { multiple: true },它可以工作,但我想同时添加多个成员。
- 我使用的是 devise gem,所以 current_user 是登录的用户。
- mutual_followers:您关注的用户,也关注您(在我的 User.rb 中定义,但我不想让我的问题太长)。
我认为我的代码不起作用,因为我将一组 user_ids 作为一个 user_id 插入,但我不知道如何解决这个问题。
附:我在这里发现了一个类似的问题:Nested Simple Form in Rails4 - has many through, save multiple records
但是,我不知道如何解决我的问题,因为我没有使用 simple_form,而且我不知道如何弥补 form_for 中的差异。
【问题讨论】:
标签: ruby-on-rails ruby activerecord form-for fields-for