开发者

Querying many to many relation in Ruby on Rails

Let's say I have an app where users could rate books开发者_如何学Python. Tables are users(id), books(id) and rating(user_id, book_id, value). I've made these models

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

I want to get a list of all (both rated and unrated) books with their ratings made by current user. It's easy in SQL with outer join but I can't figure out a way to do it in Rails 3.


According to LEFT OUTER joins in Rails 3 you'll have to specify the outer join in SQL...


it's quite simple in rails too. You probably should add a relationship in user with books as well.

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

current_user.books.includes(:ratings).all

should work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜