html - 在 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”>
<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%>
控制器如下所示:
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%>
控制器
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)}
推荐阅读
- laravel - 如何根据用户设定的日期发送预定的电子邮件?
- mongodb - 如何在嵌入(discord.js)中映射来自猫鼬数据库的数据
- logic - 理解符号逻辑(来自 BCS 学习资源书)
- android - 从android中的其他类中删除动作模式
- json - yaml:使用 go 时解组错误
- javascript - 部分未显示在移动视图上
- react-native - 如何在反应原生图像组件中显示base64和uri
- python - SQLAlchemy - 最新的多对多关系
- reactjs - 从 API 获取所有数据后如何隐藏加载更多按钮?
- linux - linux命令输出一个csv文件(里面有不同的格式)