Product
modelに対する単純な検索機能(search
メソッド)を実装しているのですが、undefined method "search"
が出てしまいます。
解決策わからず、誤りご指摘頂けますと助かります。
route
は以下の通り
ruby
1namespace :user do 2 resources :products do 3 collection {get "search"} 4 end 5end
user/products_controller
は以下の通り
ruby
1def search 2 @products = Product.search(params[:q]) 3 render "index" 4end
models/product.rb
内にsearch
メソッドを定義
ruby
1class Product < ApplicationRecord 2 3def search(query) 4 rel = order("posted_at") 5 if query.present? 6 rel=rel.where("title LIKE? OR price LIKE?", 7"%#{query}%", "%#{query}%") 8 end 9 rel 10 end 11end
テンプレートproducts/index.html.erb
内には以下記載
<%= form_tag :search_user_products, method: :get do %> <%= text_field_tag "q", params[:q], placeholder: "キーワード入力..." %>
検索実行後のログを見るとUser
モデルから検索を実行しているように見えています。。。原因はここでしょうか?ここだとしてもなぜこうなるのか、わかりません。
Started GET "/user/products/search?utf8=%E2%9C%93&q=2000&commit=Go%21" for ::1 at 2017-01-22 08:28:53 +0900 Processing by User::ProductsController#search as HTML Parameters: {"utf8"=>"✓", "q"=>"2000", "commit"=>"Go!"} User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]] Completed 500 Internal Server Error in 16ms (ActiveRecord: 0.4ms) NoMethodError (undefined method `search' for #<Class:0x007fb7042cff70>):
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/01/22 00:33