Hello guys/girls I am trying to use a search_form_for and ransack scope but it doesn't seem to work
I have a product model
class Product < ActiveRecord::Base
scope :active, -> { where(active: true)}
def self.ransackable_scopes(auth_object = nil)
[:active]
end
end
In my controller:
class ProductsController < BaseController
def example
@q = Product.ransack(params[:q])
@products = @q.result.page(params[:page])
end
end
how can I use a search form with a checkbox
that would include or exclude the desired active scope ? I've tried the code below but it doesn't seem to work
= search_form_for @q, url: products_example_path do |f|
= f.check_box :active
include or exclude the desired active scope
Do you mean true => Product.active and false => Product.all? Or do you want active vs. inactive exclusively?
Ransack can pass params to your scope if they come as an array. So, something like this is possible:
scope :active, ->(yes=true) { where(active: yes) }
# so you can do Product.active(true) and Product.active(false)
Product.search(active: [true])
Product.search(active: [false])
If Ransack receives the scope params as an array, it passes that through. (Note there are some issues with type conversion though, see #509)
I would like to do what the original question is asking here. Which is a checkbox to either apply or not the scope. Is that possible with ransack?
Yes, use true, nil as the check box values
= f.check_box :active, {}, "true", nil
Most helpful comment
Do you mean
true => Product.activeandfalse => Product.all? Or do you want active vs. inactive exclusively?Ransack can pass params to your scope if they come as an array. So, something like this is possible:
If Ransack receives the scope params as an array, it passes that through. (Note there are some issues with type conversion though, see #509)