我有表Games
和Badges
他们正在通过表BadgesGames
连接。
t.integer "badge_id"
t.integer "game_id"
t.boolean "shown", default: false
我有Game
个对象,我希望找到所有Badges
哪个wans' t shown
game_object.(condition?).badges
如何获得它?
答案 0 :(得分:6)
假设您有has_and_belongs_to_many
'通过'建立关系:
class Game < ActiveRecord::Base
has_many :game_badges
has_many :badges, through: :game_badges
end
class GameBadge < ActiveRecord::Base
belongs_to :game
belongs_to :badge
end
class Badge < ActiveRecord::Base
has_many :game_badges
has_many :games, through: :game_badges
end
然后您可以使用以下内容:
game.game_badges.where(shown: false).map(&:badge)