将ActiveRecord :: Relation与ActiveRecord :: Associations合并

时间:2014-05-30 19:58:55

标签: activerecord ruby-on-rails-4 rails-activerecord active-record-query

我有2个模特

class User < ActiveRecord::Base
    has_many :games

    def created_games
        Game.where(created_by: self.id)
    end
end

class Game < ActiveRecord::Base
    belongs_to :user
end

u = User.take
joined_games = u.games
created_games = u.created_games

变量joined_games是ActiveRecord :: Associations的实例,created_games是ActiveRecord :: Relation的实例。

我有什么方法可以一起加入joined_games和created_games吗?

1 个答案:

答案 0 :(得分:1)

尝试在用户模型中添加范围

scope :joined_games, where(user_id: self.id, created_by: self.id)