データベース内のすべての著者を表示する著者ページがあります。
<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_to
author.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