在查询结果中制作的ActiveRecord加入模型属性可用 [英] Making ActiveRecord join model attributes available in query results

查看:117
本文介绍了在查询结果中制作的ActiveRecord加入模型属性可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于用户和书款,我创建了一个连接模型,ViewedBook,包含附加属性。下面是我想出来的精髓:

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

我觉得这适用于大多数我需要创建查询。不过,我想每本书的对象由 user.viewed_books返回包含完成属性为好。此外,我会像 Book.best_sellers 其他查询,我也想范围,以给定的用户,以便它们还包括成品的属性。

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.

从我有限的接触到的ActiveRecord,看来有可能是一个优雅的方式来管理这一点,并产生高效的查询,但我还没有找到明确这种情况的一个例子。

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.

编辑:澄清,其他的疑问我在寻找自己不会被限制在已完成的书,但我需要有完成属性附加到每一本书,如果它存在,对于给定的书,在book_viewings范围内的用户。

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.

推荐答案

在这里看到我的回答 http://stackoverflow.com/a /三十六万五千八百六十五分之八百八十七万四千八百三十一

pretty的太多,没有没有一个具体的方式做到这一点,但你可以通过一个选择选项,你的has_many关联。在你的情况我会做到这一点:

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'

这篇关于在查询结果中制作的ActiveRecord加入模型属性可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆