0

在显示书籍模型时尝试从作者模型中列出作者姓名。我不确定使用 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 获取作者的名字。

4

1 回答 1

0

在 Book 模型中:

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>
于 2013-01-06T16:11:29.817 回答