2010-05-03 35 views
0

我有樹表導軌:include語句上有兩個條件

  • 書籤
  • 用戶

那裏有一個到m的關係從書籍給用戶槽書籤。

我正在尋找一個查詢,在那裏我得到了某個用戶的所有書籍,包括書籤。如果沒有書籤都在那裏,應該有包括空...

我的SQL語句類似於:

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

在鐵軌我只知道:包括語句,但我怎麼可以添加第二個書籤.user_id =?此查詢的ON部分中的語句?如果我將它放在條件部分中,則不會返回空結果!

謝謝! 馬庫斯

+1

什麼是 「N/M的關係」? – 2010-05-03 16:21:17

+0

n至m關係 – Markus 2010-05-03 16:24:44

回答

0

添加以下關聯到你的機型:

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 

現在您可以以下呼叫:

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])