2014-02-09 32 views
0

我有三個型號:的has_many thorugh需要的性能通過

User id, name, ... 
    has_many :user_books 
    has_many :books, through: :user_books 

Books id, name, author 
    has_many :user_books 

UserBooks id, user_id, book_id, has_read, rating 
    belongs_to :user 
    belongs_to :book 

好了,所以這是設置。當我做User.books時,我收到了書籍集合,但無法訪問在UserBook中設置的屬性(book.name,book.author),例如has_read,rating等。

如何閱讀「圖書」和「用戶書籍」

+0

http://stackoverflow.com/questions/18799934/has-many-through-how-do-you-access-join-table-attributes – svoop

+0

的重複,似乎並不工作 –

回答

0

你想要做的就是使用連接模型來做類似下面的事情。在控制器:

@user_books = @user.user_books.includes(:books) 

(使用包括防止n+1 queries問題,因爲它會緩存user_books需要的書籍,造成2個總查詢)

然後在視圖中,你可以做這樣的事情:

<%= @user_books.each do |user_book| %> 
    <div class="<%= 'read' if user_book.has_read? %>"> 
    <h2><%= user_book.book.name %> <small>by <%= user_book.book.author %></h2> 
    <span><%= user_book.rating %></span> 
    </div> 
<%= end %> 

如果您想包括這本書的方法,您可以使用delegate像這樣:

class UserBook < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :book 

    delegate :has_read, to: :book 
    delegate :author, to: :book 
end 

http://api.rubyonrails.org/classes/Module.html#method-i-delegate

然後,你可以做到以下幾點:

@books = @user.user_books.includes(:books) 

然後在視圖:

<%= @books.each do |book| %> 
    <div class="<%= 'read' if book.has_read? %>"> 
    <h2><%= book.name %> <small>by <%= book.author %></h2> 
    <span><%= book.rating %></span> 
    </div> 
<%= end %> 

現在明白了,雖然我們稱之爲 「書」 中的控制器和視圖,它的一個「UserBook」對象。

+0

我其實想要user_books的屬性以及同一個變量中的書,所以我可以使用user_book.book.has_read來做book.name和book.has_read。如何使用來自兩個不同對象的屬性創建新對象 –

+0

檢查更新的答案 – omarvelous