rails:包含两个ON条件的语句

时间:2010-05-03 16:02:39

标签: sql ruby-on-rails activerecord

我有树表

  • 书籍
  • 书签
  • 用户

通过书签,书籍与用户之间存在n到m的关系。

我正在寻找一个查询,在那里我获得某个用户的所有书籍,包括书签。如果没有书签,则应该包含空值...

我的sql语句如下:

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

在rails中我只知道:include语句,但是如何添加第二个bookmarks.user_id =?此查询的ON部分中的语句?如果我把它放在:conditions部分,那么就不会返回null结果!

谢谢! 马库斯

1 个答案:

答案 0 :(得分: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])