2017-02-28 135 views
0

我試圖在有多個用戶的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中的差異。

回答

0

解決此問題的一個簡單方法是使用nested_form gem。 https://github.com/ryanb/nested_form

如果你使用它,你可以添加或刪除nested_forms只需編碼如下。

<%= f.fields_for :tasks do |task_form| %> 
    <%= task_form.text_field :name %> 
    <%= task_form.link_to_remove "Remove this task" %> 
<% end %> 
<p><%= f.link_to_add "Add a task", :tasks %></p> 

寶石的自述是很容易理解的,所以你應該檢查這一點。另外,如果你看看gem提供的維基,你可以知道如何自定義表單,只要你喜歡。

相關問題