我有一个包含用户,图书馆和图书的应用。
用户拥有许多库。图书馆有很多用户和书籍。但是用户和书籍没有直接的关系。用户只能从图书馆借阅图书。
我试图获取属于用户所属图书馆的图书集。换句话说,我希望获得给定用户所属的库中的所有书籍。
要说清楚,我不想通过目前存在于用户和图书之间的借用协会,因为我想要该图书馆中的所有图书,而不仅仅是当前用户借阅的图书。
我已经尝试使用SQL和Squeel在几个小时内提出这个查询,没有运气......在此先感谢您的帮助。
答案 0 :(得分:2)
你可以这样做......
Book.where(:library_id => user.library_ids)
或者你可以这样做。鉴于此模型设置...
class Book < ActiveRecord::Base
belongs_to :library
class Library < ActiveRecord::Base
has_many :books
has_many :memberships
has_many :users, :through => :memberships
class User < ActiveRecord::Base
has_many :memberships
has_many :libraries, :through => :memberships
has_many :books, :through => :libraries
有了这个,你可以要求@user.books
,它在Rails中会产生如下的SQL:
# 1 is @user.id
SELECT "books".* FROM "books" INNER JOIN "libraries" ON "books"."library_id" = "libraries"."id" INNER JOIN "memberships" ON "libraries"."id" = "memberships"."library_id" WHERE "memberships"."user_id" = 1
答案 1 :(得分:2)
Table_User
user_id user_name library_id membership_id
Table_Library
library_id user_id book_id membership_id
Table_Books
books_id book_name library_id
Table_Membership
membership_id user_id library_id
select book_name from Table_Books
inner join Table_Library on Table_Books.library_id=Table_Library.library_id
inner join Table_User on Table_User.library_id=Table_Library.library_id
where Table_User.library_id = Table_Membership.library_id
and Table_User.user_id =Table_Membership.user_id