0

Let's say I have an app where users could rate books. 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.

synapse
  • 5,588
  • 6
  • 35
  • 65

2 Answers2

1

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

Community
  • 1
  • 1
David Sulc
  • 25,946
  • 3
  • 52
  • 54
0

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.

Aditya Sanghi
  • 13,370
  • 2
  • 44
  • 50