使用嵌套属性在另一个中显示使用ID捕获的模式

时间:2013-01-06 16:00:49

标签: ruby-on-rails ruby-on-rails-3

在显示图书模型时,尝试从作者模型列出作者姓名。我不确定使用Books模型中保存的Author_ID从Authors模型中获取列的语法。

我的两种模式的架构:

CREATE TABLE "authors" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);

CREATE TABLE "books" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "author_id" integer);

图书的index.html.erb:

<h1>Listing books</h1>

<table>
  <tr>
    <th>Title</th>
    <th>Author</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @books.each do |book| %>
  <tr>
    <td><%= book.title %></td>
    <td><%= book.author_id %></td>
    <td><%= link_to 'Show', book %></td>
    <td><%= link_to 'Edit', edit_book_path(book) %></td>
    <td><%= link_to 'Destroy', book, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New Book', new_book_path %>

当前输出

    Listing books

Title                                   Author          
Dirty Dozen                             2      Show    Edit    Destroy
Life and Times of Rich and Famous       1      Show    Edit    Destroy
Digby Manual                            4      Show    Edit    Destroy
Piano for Pros                          5      Show    Edit    Destroy
Pints and Pubs                          6      Show    Edit    Destroy

我想使用某些内容来<td><%= author.(book.author_id).name %></td>使用作者的ID获取作者姓名。

1 个答案:

答案 0 :(得分:0)

书中的

class Book < ActiveRecord::Base
  belongs_to :author
  ...
作者模型中的

class Author < ActiveRecord::Base
  has_many :books
  ...

在控制器索引操作中(以避免n + 1个查询)

@books = Book.includes(:author).all # or your criteria

最后

<td><%= book.author.name %></td>