LogofaT
LogofaT

Reputation: 289

Filters in rails for a model

How can I make a dynamic query in Rails (I'm pretty new to this framework and also to ruby).

In my controller I have:

class ProductController < ApplicationController
  def index
    @products = Product.where(active:1).paginate(:page => params[:page])
    @categories= Category.all
  end
end

And part of my view is like:

   .filter-product
      =form_tag do
        %table#id-form 
          %tr
            %th{valign: "top"} Product name:
            %td
              %input.inp-form{type: "text"}/
            %td
          %tr
            %th{valign: "top"} Category:
            %td
              %select
                %option{value: ""} All
                - @categories.each do  |cat|
                  %option{value: cat.id}= cat.label
            %td
          %tr
            %th{valign: "top"} Stock:
            %td
              %input.inp-form{type: "checkbox"}/
            %td
          %tr
            %th  
            %td{valign: "top"}
              %input.form-submit{type: "button", value: ""}/
              %input.form-reset{type: "reset", value: ""}/
            %td

I want to filter my products by title, availability(stock) and also categories. The query should also work when these are not set.

I have tried at least 3-4 ways and none of them worked.

Edit : Here are my models:

    class Product < ActiveRecord::Base
     belongs_to :category
    end

    class Category < ActiveRecord::Base
     has_many :products
    end

Upvotes: 1

Views: 613

Answers (2)

Danny
Danny

Reputation: 6025

I would definitely try to "standardize" your filters using a gem like Ransack. This way you don't have to write all code yourself, and Ransack perfectly integrates with your existing pagination. DRY also means "don't reinvent the wheel if you don't have to"...

Upvotes: 0

Pankhuri Kaushik
Pankhuri Kaushik

Reputation: 332

Please try the following way:

Product.where(active:1,"title like ?", "category_id = ?", params[:title].presence || '%%', params[:category_id].presence || Category.all.collect(&:id) ).paginate(:page => params[:page]...

I hope it works for you.

Upvotes: 1

Related Questions