Ruby on rails 有很多through需要类的属性吗

Ruby on rails 有很多through需要类的属性吗,ruby-on-rails,Ruby On Rails,我有三种型号: 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

我有三种型号:

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时,我会得到一个图书集合,但无法访问在用户手册中设置的属性(book.name、book.author),如has_read、rating等


如何阅读书籍和用户手册

您要做的是使用连接模型,执行以下操作。在控制器中:

@user_books = @user.user_books.includes(:books)
(使用include可防止出现
n+1查询
问题,因为它会缓存用户所需的书籍,导致总共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 %>

然后您可以执行以下操作:

@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 %>

通过

现在请理解,尽管我们在控制器和视图中称其为“Book”,但它是一个“UserBook”对象。

该对象的副本似乎不起作用。我实际上希望在同一变量中包含user\u books和Book的属性,以便我可以使用user\u Book.Book.has\u read执行Book.name和Book.has\u read。如何使用两个不同对象的特性创建新对象
<%= @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 %>