前提・実現したいこと
Rails で書籍検索アプリを作成しています。
link_toを用いたform送信で本の
・題名
・著者
・ログイン中のユーザーID
を取ってきてbookモデルに保存したいのですが、題名と著者はnilになってしまいます。
発生している問題・エラーメッセージ
undefined method `title' for #<Book::ActiveRecord_Associations_CollectionProxy:0x007f8f39282f88>
該当のソースコード
Ruby
1// views/books/search 2<div class="row"> 3 <div class="col-md-6 col-md-offset-3"> 4 <%= form_tag :search, method: :get do %> 5 <%= label_tag :title,'書籍名検索' %> 6 <%= text_field_tag 'title', params[:title] %> 7 <%= submit_tag "検索" %> 8 <% end %> 9 <%= form_tag :search, method: :get do %> 10 <%= label_tag :author,'著者名検索' %> 11 <%= text_field_tag 'author', params[:author] %> 12 <%= submit_tag "検索" %> 13 <% end %> 14 </div> 15</div> 16 17<table> 18 <thead> 19 <tr> 20 <th>商品名</th> 21 <th>著者名</th> 22 <th>画像</th> 23 </tr> 24 </thead> 25 <tbody> 26 <% if @items.present? %> 27 <% @items.each do |item| %> 28 <tr> 29 <td><%= link_to item.title, "#{item["itemUrl"]}" %></td> 30 <td><%= item.author %></td> 31 <td><%= image_tag item["smallImageUrl"] %></td> 32 <td><%= link_to "本棚に追加する", books_path({:book => {title: item.title, author: item.author, user_id: current_user.id}}),method: :post %></td> 33 </tr> 34 <% end %> 35 <% end %> 36 </tbody> 37</table> 38
Ruby
1// controllers/books.controller.rb 2class BooksController < ApplicationController 3 before_action :logged_in_user, only: [:create, :destroy] 4 5 def search 6 if params[:title] #書籍名で検索 7 @items = RakutenWebService::Books::Book.search(title: params[:title]) 8 elsif params[:author] #著者名で検索 9 @items = RakutenWebService::Books::Book.search(author: params[:author]) 10 end 11 12 end 13 14 15 def create 16 @book = current_user.books.build(book_params) 17 if @book.save 18 flash[:success] = "本棚に追加しました!" 19 redirect_to current_user 20 else 21 render 'search' 22 end 23 end 24 25 def destroy 26 end 27 28 private 29 30 def book_params 31 params.require(:book).permit(:title, :author, :user_id) 32 end 33end 34
Ruby
1// db/schema.rb 2create_table "books", force: :cascade do |t| 3 t.string "title" 4 t.string "author" 5 t.integer "user_id" 6 t.datetime "created_at", null: false 7 t.datetime "updated_at", null: false 8 t.index ["user_id"], name: "index_books_on_user_id" 9 end
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/10 09:41
2018/07/10 09:52