开发者

rails: include statement with two ON conditions

开发者 https://www.devze.com 2022-12-28 19:20 出处:网络
I have tree tables books bookmarks users开发者_Go百科 where there is a n to m relation from books to users trough bookmarks.

I have tree tables

where there is a n to m relation from books to users trough bookmarks.

Im looking for a query, where I get all the books of a certain user including the bookmarks. If no bookmarks are there, there should be a null included...

my sql statement looks like:

SELECT * FROM `books` 
LEFT OUTER JOIN `bookmarks ` 
ON bookmarks.book_id = books.id 
AND bookmarks.user_id = ?

In rails I only know the :include statement, but how can I add the second bookmarks.user_id = ? statement in the ON section of this query? if I put it in the :conditions part, no null results would get returned!

Thanks! Markus


Add the following associations to your models:

class Book < ActiveRecord::Base
  has_many :bookmarks
  has_many :users, :through => :bookmarks
end

# assuming bookmarks table has book_id and user_id columns.
class Bookmark < ActiveRecord::Base
  belongs_to :book
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :bookmarks
  has_many :books, :through => :bookmarks
end

Now you can make following calls:

u.books  # books for a user
u.bookmarks   # bookmarks for a user

# find the user and eager load books and bookmarks
User.find(params[:id], :include => [:books, :bookmarks])


b.users  # users for a book
b.bookmarks   # bookmarks for a book

# find the book and eager load users and bookmarks
Book.find(params[:id], :include => [:users, :bookmarks])
0

精彩评论

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