Rails SQL Where If condition

时间:2014-07-07 16:17:44

标签: sql ruby-on-rails ruby conditional where

我正在尝试为rails博客创建高级搜索表单 我试图避免使用宝石 我有一个poststitlelocation_id的表{},最后两个连接到两个表位置(:小,:更大)和类别(名称) ,但我怀疑这对这个问题很重要

我有一个搜索表单,可以查找location_id和category_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 %>

但它似乎不起作用 我需要它如此工作,如果表单有Category = Any category(:included_blank =&gt;“任何类别) 和位置=伦敦 它将搜索位置为== london的所有帖子,但它会删除该类别的.where,看到它是==任何城市,反之亦然,如果选择了类别并且位置留空(:included_blank =&gt ;“任何城市”

由于

1 个答案:

答案 0 :(得分:1)

if @advanced_search.category_search.present? && @advanced_search.location_search.present?
  Post.
    where('category_id = ?', @advanced_search.category_search).
    where('location_id = ?', @advanced_search.location_search).
    all
elsif @advanced_search.category_search.present?
  Post.
    where('category_id = ?', @advanced_search.category_search).
    all
elsif @advanced_search.location_search.present?
  Post.
    where('location_id = ?', @advanced_search.location_search).
    all
else
  Post.all
end