【发布时间】:2015-06-17 18:23:00
【问题描述】:
我已经编辑了我的第一个代码,现在由于@FunTimeFreddie,它变得更好、更清晰了,但是它的问题还没有得到妥善解决。我会尽快回复正确答案。
在搜索表单中,我需要过滤所有菜单项: 1. 按类别 2.按类别搜索“查询” 3. 每分钟价格 && ||最高价格 ……等等,所有可能的组合
我已经设法使用“查询”、min_price 和 max_price 搜索所有菜单项——搜索表单中所有可能的组合。我无法获得所选类别的结果列表,我做错了什么?
这是我的模型(已编辑):
class Menuitem < ActiveRecord::Base
belongs_to :menu_category
include Filterable
scope :newest_first, lambda { order('menuitems.created_at DESC') }
scope :last_one, lambda { order('menuitems.created_at ASC').last }
scope :search_keyword, lambda { |query|
where(["title LIKE ? or body LIKE ?", "%#{query}%", "%#{query}%"]) if query != ""
}
scope :menu_category_id, lambda { |menu_category_id|
where( "menu_category_id = ?", menu_category_id ) if menu_category_id != ""
}
scope :min_price, lambda { |price|
where("price > ?", price) if price != ""
}
scope :max_price, lambda { |price|
where("price < ?", price) if price != ""
}
end
这是我的控制器(已编辑):
class MenuitemsController < ApplicationController
def index
@menuitems = Menuitem.newest_first.filter(params.slice(:menu_category_id, :search_keyword, :min_price, :max_price))
end
这是我的观点:
<%= simple_form_for :menuitem, :method => 'get', :url => {:action => 'index'} do |f| %>
<p>
<%= f.select :menu_category_id, options_for_select(@menucategories.map {|s| [s.title, s.id]}, params[:menu_category_id]), :selected => params[:menu_category_id], :onchange => "this.form.submit();", prompt: "Select category" %>
</p>
<p>
<%= f.input :search_keyword, input_html: { name: 'search_keyword', :value => params[:search_keyword]}, label: 'search recipe title', :required => false %>
<%= f.input :min_price, input_html: { name: 'min_price', :value => params[:min_price]}, label: 'min price:', :required => false %>
<%= f.input :max_price, input_html: { name: 'max_price', :value => params[:max_price]}, label: 'max price:', :required => false %>
<%= f.button :submit, "search" %>
</p>
<% end %>
【问题讨论】:
-
作为调试方法,将您的 select 语句中的模型替换为一组虚拟文本,例如 ["Fred", "Wilma", "Barney", "Betty"]。如果这可行,您的问题是您的模型没有返回文本数组。如果它不起作用,则您的 f.select 已损坏并且需要工作,直到虚拟数组起作用。像@FunTimeFreddies 这样的 FWIW 增加答案是识别有用答案的方法。
-
这是一个很好的建议@Matt Stevens,我要试试。我已经看到 url 显示了查询,所以我认为它应该是我的控制器或模型中的问题。关于滴答,你绝对是对的,但我不能什么都不做,因为我没有足够的声誉。 :( 对不起。
标签: ruby-on-rails search scope html-select