私は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
また別の方法がありますか?何か助けていただきありがとうございます。さらに詳しい情報が必要な場合はお知らせください。私はあなたのようなブックをループだろうと考えてい
'author.books'の代わりに' author.books'を使って各著者の本をループする必要があります – thiagotonon