导航栏中的搜索功能

时间:2015-11-02 12:42:50

标签: ruby-on-rails ruby-on-rails-4

我已经在导航栏中添加了一个搜索字段(使用Bootstrap3),但我无法使其工作,除非我对产品'页。我尝试过初始化(如欢迎控制器中所见,但我不知道我做错了什么......)。我无法在不破坏某些事情的情况下工作...... 主页告诉我这个:

Couldn't find Category with 'id'=#<Category::ActiveRecord_Relation:0x5623a70>

虽然“类别”页面会抛出我:

No route matches {:action=>"index", :category_id=>nil, :controller=>"products"} missing required keys: [:category_id]

我的导航是:

 <%= form_tag(category_products_path(@category), :method => "get", id: "search-form", class: "navbar-form navbar-left") do %>
        <div class="form-group">
        <%= text_field_tag :search, params[:search], placeholder: "Search", class: "form-control" %>
        </div>
        <%= submit_tag "Search", :class => 'btn btn-default',:name => nil%>
      <% end %>

路由

resources :categories, only: [:index, :show] do
  resources :products, only: [:index, :show]
end

控制器

class WelcomeController < ApplicationController
    def index 
        @category = Category.all
        @products = Product.all
    end
end
class ProductsController < ApplicationController
    before_action :set_product, only:[:show]
    def index
        @category = Category.find(params[:category_id])
        if params[:search]
            @products = @category.products.search(params[:search]).paginate(:per_page=>10, :page=>params[:page])
        else
            @products = @category.products.paginate(:per_page=>10, :page=>params[:page])
        end
    end

    def show
    end

    private

    def set_product
      @product = Product.find(params[:id])
    end
end

class CategoriesController < ApplicationController    
    before_action :set_category, only: [:show]
    def index
      @categories = Category.all
    end

    def show
      @products = @category.products
    end

    private

    def set_category
      @category = Category.find(params[:id])
    end
end

0 个答案:

没有答案