2011-01-09 61 views
0

假设我有一个应用程序,用户可以在其中对书籍进行评分。表格是用户(id),书籍(id)和评分(user_id,book_id,值)。我做了这些模型在Ruby on Rails中查询多对多关系

class Rating < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :book 
end 

class User < ActiveRecord::Base 
    has_many :ratings 
end 

class Book < ActiveRecord::Base 
    has_many :ratings 
end 

我想(包括额定和未评级)的书与他们的当前用户所做出的所有评级的列表。这很容易在SQL与外连接,但我不能想出一个办法做到在Rails的3

回答

0

这是相当简单的轨道也。您可能应该在书籍的用户中添加关系。

class User < ActiveRecord::Base 
    has_many :ratings 
    has_many :users, :through => :ratings 
end 

current_user.books.includes(:ratings).all 

应该工作。

+0

这将返回只有评级的书,而我需要所有的人 – synapse 2011-01-09 10:12:55