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