如何遍历rails模型以获得复杂的结果(has_mas> has_many)

时间:2011-02-01 06:26:15

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

也许是我看不到的简单问题,但现在对我来说有点棘手

我需要知道用户下注了哪些项目。 我想做点什么:

some_user.bets.projects

我的模特是:

class User < ActiveRecord::Base
    has_many :bets
end
class Project < ActiveRecord::Base
    has_many :bets
end
class Bet < ActiveRecord::Base
    belongs_to :user
    belongs_to :project
end

所以,为了清楚起见,从用户实例开始,我怎么知道用户下了哪些项目。

在sql中会有类似

的内容
select projects.name from users
                inner join bets
                           on bets.user_id = users.id
                inner join projects
                           on bets.project_id = projects.id
           where users.id = 1;

如何让它发挥作用?

1 个答案:

答案 0 :(得分:4)

按以下步骤更新您的UserProject课程:

class User < ActiveRecord::Base
  has_many :bets
  has_many :projects, :through => :bets
end

class Project < ActiveRecord::Base
  has_many :bets
  has_many :users, :through => :bets
end

然后你可以这样做:

user = User.first        # Find a user
projects = user.projects # and return the projects that have bets