Win8.1 Rails 5.0.1 Ruby 2.3.3p222
表題の通りです。
コントローラにアクションを追加、
ルーティングにも追加してるんですが、
アクションを呼ぶとNoMethodErrorが表示されます。
何故でしょうか??
宜しくお願い致します。
●ルーティング
ruby
1Rails.application.routes.draw do 2 root 'products#index' 3 4 resources :products, only: [:index] do 5 collection do 6 get :search 7 end 8 end 9 10end 11
●コントローラ
ruby
1class ProductsController < ApplicationController 2 3 4 def index 5 @product = Search::Product.new 6 end 7 8 def search 9 @product = Search::Product.new(search_params) 10 @products = @product 11 .matches 12 .order(availability: :desc, code: :asc) 13 .decorate 14 end 15 16 17 def show 18 end 19 20 def new 21 @product = Product.new 22 end 23 24 def edit 25 end 26 27 private 28 29 30 # 検索フォームから受け取ったパラメータ 31 def search_params 32 params 33 .require(:search_product) 34 .permit(Search::Product::ATTRIBUTES) 35 end 36 37 38end 39
●呼出し側ビュー
Ruby
1<% content_for(:title) do %> 2 商品検索 3<% end %> 4 5<%= form_for(@product, url: search_products_path, html: { method: :get, class: 'form-horizontal', role: 'form' }) do |f| %> 6 <%= render 'search_form', f: f %> 7<% end %>
【モデル追加】
app\models\search\base.rb
Ruby
1class Search::Base 2 include ActiveModel::Model 3 include ActiveModel::Validations::Callbacks 4 5 def contains(arel_attribute, value) 6 arel_attribute.matches("%#{escape_like(value)}%") 7 end 8 9 def escape_like(string) 10 string.gsub(/[\\%_]/) { |m| "\\#{m}" } 11 end 12 13 def value_to_boolean(value) 14 ActiveRecord::ConnectionAdapters::Column.value_to_boolean(value) 15 end 16end
app\models\search\Product.rb
Ruby
1class Search::Product < Search::Base 2 ATTRIBUTES = %i( 3 code 4 name name_kana 5 price_from price_to 6 purchase_cost_from purchase_cost_to 7 availability 8 ) 9 attr_accessor(*ATTRIBUTES) 10 11 def matches 12 t = ::Product.arel_table 13 results = ::Product.all 14 results = results.where(contains(t[:code], code)) if code.present? 15 results = results.where(contains(t[:name], name)) if name.present? 16 results = results.where(contains(t[:name_kana], name_kana)) if name_kana.present? 17 results = results.where(t[:price].gteq(price_from)) if price_from.present? 18 results = results.where(t[:price].lteq(price_to)) if price_to.present? 19 if purchase_cost_from.present? 20 results = results.where(t[:purchase_cost].gteq(purchase_cost_from)) 21 end 22 if purchase_cost_to.present? 23 results = results.where(t[:purchase_cost].lteq(purchase_cost_to)) 24 end 25 results = results.where(availability: true) if value_to_boolean(availability) 26 results 27 end 28end
app\models\product.rb
Ruby
1class Product < ApplicationRecord 2end 3
回答1件
あなたの回答
tips
プレビュー