【发布时间】:2014-07-07 16:17:44
【问题描述】:
我正在尝试为 Rails 博客创建高级搜索表单
我试图避免使用宝石
我有一个表posts 和title,location_id 和category_id,最后两个连接到两个表位置(:小,:大)和类别(名称),但我怀疑这对这个很重要问题
我有一个搜索表单,可以查找 location_id 和 category_id 等于用户设置选项的所有帖子
<%= form_for(@advanced_search) do |f| %>
<div class="field">
<%= f.label :category_search %><br>
<%= f.collection_select :category_search, Category.all, :id, :name, :
include_blank => "any category" %>
</div>
<div class="field">
<%= f.label :location_search %><br>
<%= f.collection_select :location_search, Location.all, :id, :locationsmallgreat
,:include_blank => "any city" %>
<%= f.submit %>
<% end %>
我再次怀疑这对于可能比我解释的更简单的问题很重要
到目前为止,我基本上有这个
@posts = Post.all
@posts = @posts.where('category_id = ?', @advanced_search.category_search) if @advanced_search.category_search != "any category"
@posts = @posts.where('location_id = ?', @advanced_search.location_search) if @advanced_search.location_search != "any city"
但它似乎不起作用 我需要它这样工作,如果表单有 Category = Any category (:included_blank => "any category) 和位置 = 伦敦 它将搜索位置为 == london 的所有帖子,但它会删除该类别的 .where,如果选择了类别且位置留空(:included_blank => "任何城市)
谢谢
【问题讨论】:
标签: sql ruby-on-rails ruby conditional where