如何通过连接表中的条件接收对象

时间:2015-09-12 15:03:30

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

我有表GamesBadges他们正在通过表BadgesGames连接。

t.integer "badge_id"
t.integer "game_id"
t.boolean "shown",    default: false

我有Game个对象,我希望找到所有Badges哪个wans' t shown

game_object.(condition?).badges

如何获得它?

1 个答案:

答案 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)