有几种方法可以做到这一点。最简单的方法是直接添加节目:
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
如果您不想为 special 和 non-special 设置新范围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}