我有三个型号:Rails ActiveRecord - 执行包含的最佳方式?
class Book < ActiveRecord::Base
has_many :collections
has_many :users, :through => :collections
end
class User < ActiveRecord::Base
has_many :collections
has_many :books, :through => :collections
end
class Collection < ActiveRecord::Base
belongs_to :book
belongs_to :user
end
我想要显示的书籍列表,并有一个链接添加或从用户的集合中删除。我无法弄清楚这样做的最佳语法。
例如,如果我做到以下几点:
控制器
class BooksController < ApplicationController
def index
@books = Book.all
end
end
查看
...
<% if book.users.include?(current_user) %>
...
或明显的逆...
...
<% if current_user.books.include?(book) %>
...
然后查询是为每个发送书检查包括?这是浪费。我正在考虑将用户或集合添加到Book.all上的include,但我不确定这是否是最好的方法。实际上,我需要的仅仅是书籍对象,而不管当前用户是否在其集合中拥有该书籍,但我不确定如何为查询进行论坛化。
在此先感谢您的帮助。
-Damien
这似乎是最好的方式,但我遇到了混合问题:连接和:包含在同一个查找中。我的@books = Book.all真的是@books = Book.all(:include => [:authors,...]) – dwhite 2010-03-09 03:26:59
您可以使用'include'而不是'joins'。不必同时使用它们。 – 2010-03-12 08:26:01