2012-09-27 84 views
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_manybelongs_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 

回答

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:第二个例子得到N + 1负载问题。有关这方面的更多信息,请参阅A :: R指南中的eager loading一章。

注2:结帐HAML;比ERB好得多

+0

...并且请注意,您通常会通过['has_and_belongs_to_many'](http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many)执行此操作。除非每本书只有一个作者,在这种情况下'AuthorBooks'完全不需要。 – Chowlett

+1

好点。我个人已经完全停止使用HABTM关系,但它是一个很好的使用示例。 – reto

+0

我编辑了我的问题与我的模型 – Jazz