1

データベース内のすべての著者を表示する著者ページがあります。

<h1>Listing authors</h1>

<table>
  <tr>
    <th>Name</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @authors.each do |author| %>
  <tr>
    <td><%= author.name %></td>
    <td><%= link_to 'Show', author %></td>
    <td><%= link_to 'Edit', edit_author_path(author) %></td>
    <td><%= link_to 'Destroy', author, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>

<%= link_to 'New Author', new_author_path %>

著者ごとに [表示] をクリックすると、それぞれのページが表示されます。

<p>
  <b>Name:</b>
  <%= @author.name %>
</p>

<%= link_to 'Edit', edit_author_path(@author) %> |
<%= link_to 'Back', authors_path %>

これで、ユーザーが新しい本を入力したり、データベース内の本を表示および編集したりできる、本の同じ設定ができました。

has_many次に、を使用して著者と本の間の関係を保持する authorbooks というモデルを設定し、belongs_toauthor.rb、book.rb、および authorbook.rb のモデルを作成しました。

著者の番組ページに、関連するすべての本を表示したいと考えています。

これについてどうすればいいですか?私はレールに不慣れで、まだ学んでいるので、答えるときに覚えておいてください。前もって感謝します。

各モデルのモデル コードを編集します。

著者.rb

class Author < ActiveRecord::Base
  attr_accessible :name

  validates :name, :presence => true

  has_many :authorbooks
  has_many :books, :through => :authorbooks
end

book.rb

class Book < ActiveRecord::Base
  attr_accessible :name

  validates :name, :presence => true

  has_many :authorbooks
  has_many :authors, :through => :authorbooks
end

authorbook.rb

class Authorbook < ActiveRecord::Base
  attr_accessible :author_id, :book_id

  belongs_to :book
  belongs_to :author
end
4

1 に答える 1

2

モデルコードも見てみると面白かったです。私はあなたが次のようなものを持っていると仮定します:

class Author
  has_many :author_books
  has_many :books, :through => :author_books # this line might be missing,
                                             # read in the api documentation about it.

class AuthorBooks
  belongs_to :author
  belongs_to :book

これで、次のようなことができます:

<h3>Related books</h3>

<ul>
  <% @author.books.each do |book| %>
    <li><%= book.name %> <%= link_to "Details", book_path(book) %></li>
  <% end %>
</ul>

行がなければ、次の:throughようなことができたはずです:

@author.author_books.each do |ab|
  ... ab.book.name ...

注 1: 2 番目の例では、N+1 の負荷の問題が発生します。詳細については、A::R ガイドの熱心な読み込みの章を参照してください。

注 2: HAML をチェックアウトします。ERBよりずっといい

于 2012-09-27T09:03:07.503 に答える