Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I use a checkbox for including a scope with ransack? Raw #638

Closed
tagrudev opened this issue Jan 8, 2016 · 3 comments
Closed

How can I use a checkbox for including a scope with ransack? Raw #638

tagrudev opened this issue Jan 8, 2016 · 3 comments

Comments

@tagrudev
Copy link

tagrudev commented Jan 8, 2016

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
@avit
Copy link
Contributor

avit commented Feb 17, 2016

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)

@asecondwill
Copy link

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?

@vanboom
Copy link

vanboom commented Feb 10, 2021

Yes, use true, nil as the check box values

        = f.check_box :active, {}, "true", nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants