首页 > 解决方案 > 在 Rails 中按类别下拉搜索

问题描述

我目前正在尝试按类别功能实现简单的下拉搜索。但是,我似乎遇到了一些问题——我的搜索功能似乎不起作用。我的模型中的搜索功能是这样的:

class Image < ApplicationRecord
    belongs_to :user

    has_one_attached :image

    #validates :image, attached: true, content_type: %w(image/jpg image/jpeg image/png)

    def self.search(search)
        if search
            images = Image.all
            images = Image.where(meal_category: search[:":meal_category"][","])
            return images
        else
            Image.all
        end
    end

表格如下所示:

<%= form_tag(images_path, method: "get") do %>
                  <select name= image[:thing], class=“form-control”&gt;
                    <option value=“None”&gt;Meal Category</option>
                    <option value=“Breakfast”&gt;Breakfast</option>
                    <option value=“Lunch/Dinner”&gt;Lunch/Dinner</option>
                    <option value=“Dessert”&gt;Dessert</option>
                  </select>
                  <input type="submit" value="Submit">
                <%end%>

控制器如下所示:

class ImagesController < ApplicationController
  before_action :set_image, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:show, :index, :submit]
  before_action :correct_user, only: [:edit, :update, :destroy]

  # GET /images
  # GET /images.json
  def index
    @images = Image.search(params[:thing])
  end

最后,我的路线配置如下:

Rails.application.routes.draw do
  resources :images
  devise_for :users
  get '/upload', to: 'images#new'
  root 'images#index'
  get "/search", to: "images#search"
  get '/@:username', to: 'users#show', as: :profile
  resources :images, only: [:index, :show, :create]

  delete 'images/:id(.:format)', :to => 'images#destroy'
end

似乎我的参数没有正确传递。我尝试使用这些参数,但我未能确定问题所在。任何帮助或见解将不胜感激。提前致谢!

标签: htmlruby-on-railsrubyruby-on-rails-4

解决方案


一些细微的变化,你能看看这是否更符合你的预期:

形式

<%= form_tag(images_path, method: "get") do |f| %>
  <%= select_tag(:thing, options_for_select(@select_options)) %>
  <%= submit_tag "Search" %>
<%end%>

控制器

class ImagesController < ApplicationController
  before_action :set_image, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:show, :index, :submit]
  before_action :correct_user, only: [:edit, :update, :destroy]

  # GET /images
  # GET /images.json
  def index
    @select_options = {
      "None": "Meal Category", 
      "Breakfast": “Breakfast”,
      "Lunch/Dinner": “Lunch/Dinner”,
      "Dessert": “Dessert”
    }
    @images = Image.all
    @images = @images.search(params[:thing]) if params[:thing] && params[:thing] != "None"
  end

班级

class Image < ApplicationRecord
  belongs_to :user
  has_one_attached :image

  #validates :image, attached: true, content_type: %w(image/jpg image/jpeg image/png)

  scope :search, ->(search_text) {where(meal_category: search_text)}

推荐阅读