Making ActiveRecord join model attributes available in query results

别说谁变了你拦得住时间么 提交于 2019-12-11 12:49:30

问题


Given User and Book models, I've created a join model, ViewedBook, that contains additional attributes. Below is the essence of what I've come up with:

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

I think this works for most of the queries I need to create. However, I want each of the Book objects returned by user.viewed_books to include the finished attribute as well. Further, I will have additional queries like Book.best_sellers that I would also like to scope to a given user so that they also include the finished attribute.

From my limited exposure to ActiveRecord, it appears there's probably an elegant way to manage this and generate efficient queries, but I have yet to find an example that clarifies this scenario.

EDIT: to clarify, the other queries I'm looking for will not themselves be restricted to books that have been finished, but I need to have the finished attribute appended to each book if it exists for the given book and scoped user in book_viewings.


回答1:


See my answer here https://stackoverflow.com/a/8874831/365865

Pretty much, no there isn't a specific way to do this, but you can pass a select option to your has_many association. In your case I'd do this:

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


来源:https://stackoverflow.com/questions/9290100/making-activerecord-join-model-attributes-available-in-query-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!