我试图在有多个用户的SNS应用程序中创建一个组。 通过Groups_users组has_many用户。Rails:嵌套窗体,创建多个子记录
这里我有一个表单来创建一个组,并且我想同时向组中添加成员(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
浏览:
组/ index.html.slim
注:
- 如果我删除{多:真}从视图文件,它的工作,但我想同时添加几个成员。
- 我使用的是设计宝石,所以current_user是登录的用户。
- mutual_followers:你跟随的用户谁也跟着你(在我的User.rb中定义,但我不想让我的问题太长)。
我想我的代码不起作用,因为我插入一个user_id数组作为一个user_id,但我不知道如何解决这个问题。
P.S.我在这里发现了一个类似的问题:Nested Simple Form in Rails4 - has many through, save multiple records
但是,我无法找到如何解决我的问题,因为我没有使用simple_form,我无法弄清楚如何弥补form_for中的差异。