PMP
PMP

Reputation: 231

Rails SQL Where If condition

I am trying to create an advanced search form for a rails blog I'm trying to avoid using a gem I have a table posts with a title, location_id and category_id, the last two are connected to two tables Location (:small, :greater) and Category (name), but I doubt that's important for this question

I have a search form which finds all posts where location_id and category_id is equal to the user set option

<%= 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 %>

Once again i doubt that's important for the question which is probably simpler than I'm explaining it to be

Basically I have this so far

@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"

But it doesn't seem to work I need it to work as so, If the form has Category = Any category (:included_blank => "any category) and Location = London It would search for all Posts where location is == london, BUT it would remove the .where for the category, seeing that it is == any city and vice versa if a Category was selected and Location was left blank (:included_blank => "any city)

Thanks

Upvotes: 1

Views: 3542

Answers (1)

bjhaid
bjhaid

Reputation: 9752

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

Upvotes: 1

Related Questions