也许是我看不到的简单问题,但现在对我来说有点棘手
我需要知道用户下注了哪些项目。 我想做点什么:
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;
如何让它发挥作用?
答案 0 :(得分:4)
按以下步骤更新您的User
和Project
课程:
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