简体   繁体   中英

rails: include statement with two ON conditions

I have tree tables

  • books
  • bookmarks
  • users

where there is an 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])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM