有幾種方法可以做到這一點。最簡單的方法是直接加入顯示:
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}
謝謝你這麼多,一個非常優雅的解決方案。 –