2016-06-17 2 views
0

私はRails 4を使った簡単なプロジェクトを進めています。私は2つのモデル、AuthorとBooksを持っています。モデルは次のように見えるように、私は現在、それを持っている:2つのモデルのレールとその組み立て方法

class Author < ActiveRecord::Base 
    has_many :books 
end 

class Book < ActiveRecord::Base 
    belongs_to :author 
end 

著者コントローラは次のようになります。

class AuthorsController < ApplicationController 

def index 
    @authors = Author.all 
    @book = Book.find(params[:author_id]) 
    (Not sure if the @book line is right) 
end 

私のスキーマは次のようになりますように、私はそれを持って

create_table "authors", force: :cascade do |t| 
    t.string "name" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

    create_table "books", force: :cascade do |t| 
    t.string "title" 
    t.string "genre" 
    t.string "description" 
    t.integer "author_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 

私の本index.html.erb私は本を書いた著者を見ることができます。例:<%= book.author.name%>。それは私が望むのと同じように機能します。著者のindex.html.erbページで、著者が所属するすべての書籍を表示します。 <% = author.book.title:

<h1>All Authors</h1> 
<p><%= link_to "New", new_author_path, class: "btn btn-primary" %></p> 

<div class="container"> 
    <div class="row"> 
    <% @authors.each do |author| %> 
     <h1><%= author.name %></h1> 
     <p><%= author.book.title %></p> 
     <%= link_to "Show", author_path(author), class: "btn btn-primary" %> 
     <%= link_to "Edit", edit_author_path(author), class: "btn btn-warning"  
     %> 
     <%= link_to "Delete", author_path(author), method: :delete, data: { 
     confirm: "Are you Sure?" }, class: "btn btn-danger" %> 
    <% end %> 
    </div> 
</div> 

私は信じている、との助けを必要とメインラインは、次のようである:著者のindex.html.erbページ

私には、以下の持っています%>また、私の主な質問は、私が著者のインデックスページに書いたすべての本を見るように、どうすれば入手できますか?

resources :posts do 
    resources :comments 
    end 

また別の方法がありますか?何か助けていただきありがとうございます。さらに詳しい情報が必要な場合はお知らせください。私はあなたのようなブックをループだろうと考えてい

+0

'author.books'の代わりに' author.books'を使って各著者の本をループする必要があります – thiagotonon

答えて

0

:上記

<h1>All Authors</h1> 
<p><%= link_to "New", new_author_path, class: "btn btn-primary" %></p> 

<div class="container"> 
    <div class="row"> 
    <% @authors.each do |author| %> 
     <h1><%= author.name %></h1> 
     <% author.books.each do |book| %> 
     <p><%= book.title %></p> 
     <% end %> 
     <%= link_to "Show", author_path(author), class: "btn btn-primary" %> 
     <%= link_to "Edit", edit_author_path(author), class: "btn btn-warning"  
     %> 
     <%= link_to "Delete", author_path(author), method: :delete, data: { 
     confirm: "Are you Sure?" }, class: "btn btn-danger" %> 
    <% end %> 
    </div> 
</div> 

は動作しますが、それは(N + 1)のクエリにつながるとして、それは効率的ではありません。

この問題を回避する方法は次のとおりです。あなたのコントローラで

def index 
    @authors = Author.includes(:books) 
end 

これはまだあなたのデータベースを遅くしますが、制限とページの区切りを追加すると、その問題を解決するのを助けることができます。

+0

これは機能します!ありがとうございました! –

関連する問題