2016-01-30 34 views
2

標記用戶的最佳方法是什麼?如果你有一個團隊模型,並且當你創建一個團隊,你想添加成員,這個架構將如何工作?Rails 4在模型上標記用戶

我在考慮只使用行爲作爲切換,並將其用於用戶,但不知道這是否是最好的方法?那裏有另外一個能做這種事情的寶石嗎?

回答

2

這聽起來像你正在尋找一個has many through的關係。這需要您有一個名爲team_members的加入表來記錄哪些用戶是每個團隊的成員,其中有user_idteam_id列。因此,例如,你的團隊模式將有一個關係,看起來像這樣:

has_many :users, through: :team_members 

這則定義用於添加,查詢和刪除用戶對團隊的適當方法。

更多信息here

+0

嵌套屬性呢?這個方法也能工作嗎? – hellomello

+0

是的,您可以擁有用戶和加入模型的嵌套屬性。看看[這](https://robots.thoughtbot.com/accepts-nested-attributes-for-with-has-many-through)如果你正在努力 – tpbowden

0

爲了增加@tpbowden的答案,如果你只是想‘標籤’的用戶,您可能希望使用has_and_belongs_to_many

# app/models/user.rb 
class User < ActiveRecord::Base 
    has_and_belongs_to_many :teams 
end 

# join table "teams_users" - team_id | user_id 

# app/models/team.rb 
class Team < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

這將允許您使用該singular_collection_ids方法,與您就可以定義哪些用戶是在一個「團隊」:

#app/controllers/teams_controller.rb 
class TeamsController < ApplicationController 
    def edit 
    @team = Team.find params[:id] 
    end 

    def update 
    @team = Team.find params[:id] 
    @team.update team_params 
    end 

    private 

    def team_params 
    params.require(:team).permit(user_ids: []) 
    end 
end 

#app/views/teams/edit.html.erb 
<%= form_for @team do |f| %> 
    <%= f.collection_select :user_ids, User.all, :id, :name %> 
    <%= f.submit %> 
<% end %> 

這是接近「標記」,因爲你將得到沒有任何額外的依賴。

+0

嵌套屬性的工作呢?有什麼區別? – hellomello

+0

在這個答案的代碼中,'nested_attributes'只有當你想創建一個'group' /'user'作爲關聯對象時才需要。如果您只想將用戶分配到現有的組,上述就足夠了 –

相關問題