1
我有一个作者页面,显示数据库中的所有作者。Ruby on Rails:显示2个模型之间的关系
<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 %>
现在我已经设置了书籍,用户可以在其中输入新书籍,在数据库中显示和编辑书籍。
然后,我在author.rb,book.rb和authorbook.rb的模型中使用has_many
和belongs_to
建立了一个名为authorbooks的模型,该模型持有作者和书籍之间的关系。
我希望作者的展示页面能够显示他们相关的每本书。
我该怎么办?我是新来的铁轨,仍然在学习,所以请记得回答。提前致谢。每个模型
EDIT型号代码:
author.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
...并且请注意,您通常会通过['has_and_belongs_to_many'](http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many)执行此操作。除非每本书只有一个作者,在这种情况下'AuthorBooks'完全不需要。 – Chowlett
好点。我个人已经完全停止使用HABTM关系,但它是一个很好的使用示例。 – reto
我编辑了我的问题与我的模型 – Jazz