【问题标题】:Rails SQL Where If conditionRails SQL Where If 条件
【发布时间】:2014-07-07 16:17:44
【问题描述】:

我正在尝试为 Rails 博客创建高级搜索表单 我试图避免使用宝石 我有一个表poststitlelocation_idcategory_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


    【解决方案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
    

    【讨论】:

    • 感谢您的回答,但这似乎只显示所有帖子而不是过滤
    • 您是否将any_location 作为location_id 存储在您的数据库中
    • "any location (city)" 只是表单collection_select框中的文本,有一个空白选项&lt;%= f.collection_select :location_search, Location.all, :id, :small,:include_blank =&gt; "any city" %&gt;
    • 所以我又试了一次,我仍然收到所有帖子,但后来我想可能是因为它没有识别“任何城市”和/或“任何类别”。我选择了任何城市并在我的 show.html.erb &lt;% if @advanced_search.location_search == "any city" %&gt;&lt;h1&gt;HELLO&lt;/h1&gt;&lt;% end %&gt; 中使用了它,当然,它没有打印 Hello,所以它让我得出结论,也许 rails 没有注册“任何城市”。我尝试在您对 .blank 的回答中更改 != "any city" 和 != "any category"?但它仍然只会显示所有帖子。想法?
    • 我真的不知道@advanced_search 是什么,你可能想记录它,看看rails 在日志中返回了什么
    猜你喜欢
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 2019-11-22
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多