如何接收连接表中根据条件的对象 [英] how to receive objects by condition in connecting table

查看:120
本文介绍了如何接收连接表中根据条件的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表游戏徽章他们连接由表 BadgesGames

I have table Games and Badges they are connecting by table BadgesGames.

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

我有游戏对象,我想找到所有徽章这wans't 显示

I have Game object and i want find all Badges which wans't shown

game_object.(condition?).badges

如何获得的呢?

How to get it?

推荐答案

假设你有一个 has_​​and_belongs_to_many '到'关系成立:

Assuming you have a has_and_belongs_to_many 'through' relationship set up:

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

然后你可以用下面的:

Then you can use the following:

game.game_badges.where(shown: false).map(&:badge)

这篇关于如何接收连接表中根据条件的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆