使ActiveRecord连接模型属性在查询结果中可用

鉴于User和Book模型,我创建了一个包含其他属性的连接模型ViewedBook。 以下是我提出的内容的本质:

create_table "users" t.string "username" end create_table "books" t.string "title" t.integer "user_id" t.date "authored_date" end create_table "books_viewings" t.integer "book_id" t.integer "user_id" t.boolean "finished" t.date "last_viewed_date" end class User belongs_to :book_viewing has_many :authored_books, :class_name => "Book", :source => :book has_many :book_viewings has_many :viewed_books :through => :book_viewings :order => "book_viewings.last_viewed_date DESC" has_many :finished_books :through => :book_viewings :conditions => "book_viewings.finished = TRUE", :order => "book_viewings.last_viewed_date DESC" end class Book belongs_to :user has_one :author, :class_name => "User" end class BookViewing belongs_to :book belongs_to :user end 

我认为这适用于我需要创建的大多数查询。 但是,我希望user.viewed_books返回的每个Book对象也包含finished属性。 此外,我还有其他查询,例如Book.best_sellers ,我也希望将其范围扩展到给定用户,以便它们也包含已完成的属性。

从我对ActiveRecord的有限曝光,似乎可能有一种优雅的方式来管理它并生成有效的查询,但我还没有找到一个澄清这种情况的例子。

编辑:澄清一下,我正在寻找的其他查询本身并不局限于已经完成的书籍,但如果在book_viewings中存在给定书籍和作用域用户,我需要将finished属性附加到每本书。

请参阅我的回答https://stackoverflow.com/a/8874831/365865

实际上,没有特定的方法可以执行此操作,但您可以将选择选项传递给has_many关联。 在你的情况下我会这样做:

 has_many :books, :through => :book_viewings, :select => 'books.*, book_viewings.finished as finished'