2013-06-30 74 views
0

我有一個多對多的關係,一個使用過的模型:Rails的多對多,記錄添加額外的信息

game.rb:

has_many :shows, dependent: :destroy 
has_many :users, :through => :shows 

user.rb

has_many :shows 
has_many :games, :through => :shows 

show.rb

belongs_to :game 
belongs_to :user 

現在我追加遊戲用戶是這樣的:

game.users << special_users 
game.users << non_special_users 

雖然將用戶添加到遊戲中,我想說明,在表演元素看時什麼類型的用戶的一種方式,我知道它是從一個特殊的用戶來。我怎樣才能做到這一點? 請注意,特殊用戶是動態的,所以在其他地方找不到,它只能在遊戲和用戶之間的關係中找到。

回答

2

有幾種方法可以做到這一點。最簡單的方法是直接加入顯示:

game.shows << special_users.map{|u| Show.new(user: u, special: true) } 
game.shows << non_special_users.map{|u| Show.new(user: u, special: false) } 

或者,你可以創建一個有「特殊」的條件烤入協會:

#game.rb 
has_many :special_shows, lambda{ where(special: true) }, class_name: 'Show' 
has_many :non_special_shows, lambda{ where(special: false) }, class_name: 'Show' 
has_many :special_users, through: :special_shows, source: user 
has_many :non_special_users, through: :non_special_shows, source: user 

game.special_users << special_users 
game.non_special_users << non_special_users 

如果你不想設置了特殊和非特殊shows一個新的範圍,你可以在users協會的區別:

has_many :shows 
has_many :special_users, lambda{ where(shows: {special: true}) }, through: :shows, source: :user 
has_many :non_special_users, lambda{ where(shows: {special: false}) }, through: :shows, source: :user 

注意,在早期版本的Rails ,不支持lambda作用域條件。在這種情況下,conditions:值添加到選項哈希:

has_many :special_shows, class_name: 'Show', conditions: {special: true} 
has_many :non_special_shows, class_name: 'Show', conditions: {special: false} 
+0

謝謝你這麼多,一個非常優雅的解決方案。 –