質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.49%
Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Q&A

解決済

2回答

2216閲覧

検索機能がうまく機能しません

c.koki

総合スコア14

Ruby

Rubyはプログラミング言語のひとつで、オープンソース、オブジェクト指向のプログラミング開発に対応しています。

Ruby on Rails

Ruby on Railsは、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

0グッド

0クリップ

投稿2019/06/09 04:18

indexで検索機能を実装中(この検索機能はtitle,などを検索するとその検索結果に引っかかったもののみ出るというものにしたいです)
検索機能でエラーが出てしまいます

No route matches {:action=>"show", :controller=>"information"}, missing required keys: [:id]

https://qiita.com/yusuko/items/cff4e46aeafbc3beecf2
このサイトを参考に検索機能を作っていたのですが、

index.html.erb

ruby

1 <% content_for :header do %> 2<section class="hero is-warning"> 3 <div class="hero-body"> 4 <div class="container"> 5 <h1 class="title"> 6 Browse the latest test information 7 </h1> 8 </div> 9 </div> 10</section> 11 12<%= form_tag information_path, :method => 'get' do %> 13 <p> 14 <%= text_field_tag :search, params[:search] %> 15 <%= submit_tag "Search", :name => nil %> 16 </p> 17<% end %> 18<% end %> 19 20<div class="instrument-index-grid pt4"> 21 <% @informations.each do |information| %> 22 23 <div class="instrument border-light"> 24 <div class="instrument-thumb"> 25 <%= link_to image_tag(information.image_url(:thumb)), information %> 26 27 <% if information.condition? %> 28 <div class="condition"> 29 <span class="tag is-dark"><%= information.condition %></span> 30 </div> 31 <% end %> 32 </div> 33 34 35 <div class="pa3"> 36 37 <h3 class="fw7 f4 title"><%= link_to information.title, information %></h3> 38 39 <p class="has-text-gray fg pt1">Post by <%#= information.user.name %></p> 40 41 42 <% if information_author(information) %> 43 <%= link_to 'Edit', edit_information_path(information), class: "button is-small" %> 44 <%= link_to 'Delete', information, method: :delete, data: { confirm: "Are you sure ?" }, class: "button is-small" %> 45 <% end %> 46 47 </div> 48 </div> 49 <% end %> 50</div>

information_controller

ruby

1 class InformationController < ApplicationController 2 before_action :set_information, only: [:show, :edit, :update, :destroy] 3 before_action :authenticate_user!, except: [:index, :show] 4 # GET /information 5 # GET /information.json 6 def index 7 @informations = Information.search(params[:search]) 8 end 9 10 # GET /information/1 11 # GET /information/1.json 12 def show 13 end 14 15 # GET /information/new 16 def new 17 @information = current_user.informations.build 18 end 19 20 # GET /information/1/edit 21 def edit 22 end 23 24 # POST /information 25 # POST /information.json 26 def create 27 @information = current_user.informations.build(information_params) 28 29 respond_to do |format| 30 if @information.save 31 format.html { redirect_to @information, notice: 'Information was successfully created.' } 32 format.json { render :show, status: :created, location: @information } 33 else 34 format.html { render :new } 35 format.json { render json: @information.errors, status: :unprocessable_entity } 36 end 37 end 38 end 39 40 # PATCH/PUT /information/1 41 # PATCH/PUT /information/1.json 42 def update 43 respond_to do |format| 44 if @information.update(information_params) 45 format.html { redirect_to @information, notice: 'Information was successfully updated.' } 46 format.json { render :show, status: :ok, location: @information } 47 else 48 format.html { render :edit } 49 format.json { render json: @information.errors, status: :unprocessable_entity } 50 end 51 end 52 end 53 54 # DELETE /information/1 55 # DELETE /information/1.json 56 def destroy 57 @information.destroy 58 respond_to do |format| 59 format.html { redirect_to information_index_url, notice: 'Information was successfully destroyed.' } 60 format.json { head :no_content } 61 end 62 end 63 64 private 65 # Use callbacks to share common setup or constraints between actions. 66 def set_information 67 @information = Information.find(params[:id]) 68 end 69 70 # Never trust parameters from the scary internet, only allow the white list through. 71 def information_params 72 params.require(:information).permit(:condition, :title, :description, :image) 73 end 74end

information.rb

ruby

1def self.search(search) #ここでのself.はUser.を意味する 2 if search 3 where(['name LIKE ?', "%#{search}%"]) #検索とnameの部分一致を表示。User.は省略 4 else 5 all #全て表示。User.は省略 6 end 7 end

idがないとなっているのですが、どこでidを渡せばいいのかわかりません
showではidは渡してあります

回答お願いします!

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答2

0

細かいところは分からないので現在のエラーだけ・・
ルーティングの指定がRailsのデフォルトに則っていると仮定するとフォームに渡しているパスが間違っていると思います。

<%= form_tag information_path, :method => 'get' do %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %> </p> <% end %>

Railsのデフォルトのルーティングではindexには複数形の名前付きヘルパー、showには単数形の名前付きヘルパーが紐付けられます。

よって上記のinformation_pathは informationのshow(information/:id)にパラメーターを送信するフォームになっていて、idを指定していないため「missing required keys: [:id]」となります。

コントローラーを見ると検索時にパラメータを渡したいのはindexアクションのほうなので
informations_path とすれば良いと思います。

※informationが不加算名詞なのでヘルパー名が違うかもしれません
rails routesで information#indexの名前付きヘルパーを確認してください。

投稿2019/06/14 08:03

hellomartha

総合スコア329

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

c.koki

2019/06/14 08:28

ありがとうございます、解決しました
guest

0

ベストアンサー

route.rbにマッチしてないエラーが吐き出されていそうです。

なので、routes.rbで以下を追加して見てください。

resources :users do(userテーブルと勝手に解釈しました) ---->ここから collection do get :index end

ここでは、idを特定してしまっては検索の意味がないので、:id はいらないので、memberではなくcollection を採用しています。

投稿2019/06/09 06:15

編集2019/06/09 06:17
bamboo-nova

総合スコア1408

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

c.koki

2019/06/09 08:41

回答ありがとうございます routes.rbで resources :information do collection do get :index end end としてみましたが No route matches {:action=>"show", :controller=>"information"}, missing required keys: [:id] というエラーがまた出てしまいます。 お手数ですが返信お願いします
bamboo-nova

2019/06/09 16:14 編集

すみません、get: searchとしてください汗 これで、information/searchというパスが生成されます。 その後に、index.html.erbの検索フォームで ``` <%= form_tag search_information_path, :method => 'get' do %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %> </p> <% end %> ``` のように search_information_pathとrouteを変更すれば行けると思います。パス名が間違っていたらrails routesコマンドで確認してください。 ご迷惑をお掛けしました... 原因ですが、与える:idがなかったので、該当するルートのパスが見当たらなかったのが原因ですので、パスをroutes.rbで通してあげて、それに対応するようにビューのフォームのパスを変更すればいけます。
c.koki

2019/06/10 04:12

<%= form_tag search_information_path, :method => 'get' do %>でエラーが出たので以下のようにしてみました、そうすると検索を実行した時に The action 'search' could not be found for InformationControllerと出てしまいますコントローラーは def index @informations = Information.search(params[:search]) endのようにしています。 <%= form_tag search_information_index_path, :method => 'get' do %> <p> <%= text_field_tag :search, params[:search] %> <%= submit_tag "Search", :name => nil %> </p> <% end %> お忙しいとは思いますが返信いただけると幸いです。
bamboo-nova

2019/06/10 05:26

すみません、rails routesの結果を見せていただいてもよろしいでしょうか汗
c.koki

2019/06/10 06:20

ec2-user:~/environment/testinformation (master) $ rails routes Prefix Verb URI Pattern Controller#Action line_items GET /line_items(.:format) line_items#index POST /line_items(.:format) line_items#create new_line_item GET /line_items/new(.:format) line_items#new edit_line_item GET /line_items/:id/edit(.:format) line_items#edit line_item GET /line_items/:id(.:format) line_items#show PATCH /line_items/:id(.:format) line_items#update PUT /line_items/:id(.:format) line_items#update DELETE /line_items/:id(.:format) line_items#destroy carts GET /carts(.:format) carts#index POST /carts(.:format) carts#create new_cart GET /carts/new(.:format) carts#new edit_cart GET /carts/:id/edit(.:format) carts#edit cart GET /carts/:id(.:format) carts#show PATCH /carts/:id(.:format) carts#update PUT /carts/:id(.:format) carts#update DELETE /carts/:id(.:format) carts#destroy search_information_index GET /information/search(.:format) information#search information_index GET /information(.:format) information#index POST /information(.:format) information#create new_information GET /information/new(.:format) information#new edit_information GET /information/:id/edit(.:format) information#edit information GET /information/:id(.:format) information#show PATCH /information/:id(.:format) information#update PUT /information/:id(.:format) information#update DELETE /information/:id(.:format) information#destroy new_user_session GET /users/sign_in(.:format) devise/sessions#new user_session POST /users/sign_in(.:format) devise/sessions#create destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit user_password PATCH /users/password(.:format) devise/passwords#update PUT /users/password(.:format) devise/passwords#update POST /users/password(.:format) devise/passwords#create cancel_user_registration GET /users/cancel(.:format) registrations#cancel new_user_registration GET /users/sign_up(.:format) registrations#new edit_user_registration GET /users/edit(.:format) registrations#edit user_registration PATCH /users(.:format) registrations#update PUT /users(.:format) registrations#update DELETE /users(.:format) registrations#destroy POST /users(.:format) registrations#create root GET / information#index rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create となっています
bamboo-nova

2019/06/10 06:47 編集

Information.searchは初期値だとMember(null)になるので、 def index @informations = [] result = Information.search(params[:search]) @informations = result end として見てくれませんでしょうか。多分、indexに飛んだ際にNULLになっているためっぽいです。 また、よく見るとindexアクションで検索機能を実装しているため、 routes.rbで resources :information do collection do get : search end end は削除してください汗 これは、searchというパスを作成して、そのページに新しく検索機能を実装するときのやり方でした汗
c.koki

2019/06/10 11:00

返信ありがとうございます。 <%= form_tag information_path, :method => 'get' do %>とすると No route matches {:action=>"show", :controller=>"information"}, missing required keys: [:id]となり、 <%= form_tag search_information_path, :method => 'get' do %>とすると undefined local variable or method `search_information_path' for #<#<Class:0x00007f50c84c52a0>:0x00007f50c900dc48> となり、<%= form_tag search_information_index_path, :method => 'get' do %>としてもエラーが出てしまいます。 どうすればいいでしょうか? def index @informations = [] result = Information.search(params[:search]) @informations = result endとしました
bamboo-nova

2019/06/10 11:41

これは、定義されていない変数が定義されているということなので、search_information_pathはもう存在しないため、information_index_pathに変換すれば進むと思います。
c.koki

2019/06/10 12:28

そこのエラーはなくなったのですが <% @informations.each do |information| %> の部分でエラーが出てきて、 SQLite3::SQLException: no such column: name: SELECT "information".* FROM "information" WHERE (name LIKE '%ai%')となってしまうので、 modelの確認をしたのですが問題が無いように思います def self.search(search) #ここでのself.はUser.を意味する if search where(['name LIKE ?', "%#{search}%"]) #検索とnameの部分一致を表示。User.は省略 else all #全て表示。User.は省略 end end selfのところをInformationに変えても同じエラーでした
bamboo-nova

2019/06/10 15:36

def self.search(search) #ここでのself.はUser.を意味する if search where(['name LIKE ?', "%#{search}%"]) #検索とnameの部分一致を表示。User.は省略 else all #全て表示。User.は省略 end end モデル部分のプログラムですが、where句を使いたい場合は、そのモデルを先に記載する必要がありますので、一例ですが def self.search(search) return Information.all unless search Information.where(['name LIKE ?', "%#{search}%"]) end とする必要があるかなと思います。Informationは推測で勝手に記載したので、適宜直していただければと思います。
c.koki

2019/06/10 23:11

def self.search(search) return Information.all unless search Information.where(['name LIKE ?', "%#{search}%"]) end としても <% @informations.each do |information| %>の部分で SQLite3::SQLException: no such column: name: SELECT "information".* FROM "information" WHERE (name LIKE '%aiu%') というエラーが検索してときに出てしまいます。
bamboo-nova

2019/06/11 00:57

あ、そこのエラーだったんですね。 そこは、最初は@informationが何もないっていないのにeachを回しているので、それに関するエラーです。ですので、@informationにデータが入っているかいないかでif文でフィルタをすれば行けると思います。
c.koki

2019/06/11 01:43

返信ありがとうございます <% if @informations.present? %> <% @informations.each do |information| %>としてみたのですが <% if @informations.present? %>の部分でSQLite3::SQLException: no such column: name: SELECT "information".* FROM "information" WHERE (name LIKE '%ai%')と出てしまいます。 また検索ボタンを押した時にでるエラーなので@informationにデータは入っていると思うのですがどうすればいいでしょうか?
bamboo-nova

2019/06/11 02:59

informationsテーブルにnameというカラムはあるのでしょうか?
c.koki

2019/06/11 04:44

sqlite> .schema information CREATE TABLE "information" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "condition" varchar, "title" varchar, "description" varchar, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "image" varchar, "user_id" integer); ないです、nameはuserのことだと思います
bamboo-nova

2019/06/11 07:45

すみません、何を検索したいのかが分からないです。 ユーザの名前を検索したいのでしょうか。 それならば、informationsテーブルではなくusersテーブルを使用するように何箇所か書き換えれば行けると思います。あとはモデル側の問題だと思います。
c.koki

2019/06/11 14:22

違います。titleなどを検索すると出てくる仕組みにしたいです。 https://gyazo.com/5172d3794ee223aac566f3623f461d8d 現在こんな風になっているのでaiueoとしたらaiueo というtitleのもののみヒットするという仕組みにしたいです
bamboo-nova

2019/06/13 06:10

タイトルの名前が入っているモデルは何でしょうか? 多分、それがわかれば後はそのモデルに置き換えるだけだと思います。
c.koki

2019/06/14 08:27

うまくいきました、ありがとうございます
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.49%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問