[英]Drop Down Search by Category in Rails
我目前正在尝试按类别功能实现简单的下拉搜索。 但是,我似乎遇到了一些问题——我的搜索功能似乎不起作用。 在我的 model 中搜索 function 是这样的:
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
forms 看起来像这样:
<%= form_tag(images_path, method: "get") do %>
<select name= image[:thing], class=“form-control”>
<option value=“None”>Meal Category</option>
<option value=“Breakfast”>Breakfast</option>
<option value=“Lunch/Dinner”>Lunch/Dinner</option>
<option value=“Dessert”>Dessert</option>
</select>
<input type="submit" value="Submit">
<%end%>
controller 看起来像这样:
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
似乎我的参数没有正确传递。 我尝试使用这些参数,但我未能确定问题所在。 任何帮助或见解将不胜感激。 提前致谢!
一些细微的变化,你能看看这是否更符合你的预期:
形式
<%= form_tag(images_path, method: "get") do |f| %>
<%= select_tag(:thing, options_for_select(@select_options)) %>
<%= submit_tag "Search" %>
<%end%>
controller
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
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)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.