Denis Tataurov
Denis Tataurov

Reputation: 193

Add custom ransacker that uses scope with multiple conditions

I'm using Ransack gem and I have a model that has a scope like this:

scope :by_attr, ->(attr) {
  case attr
  when val1
    query1
  when val2
    query2
  else
    all
  end
}

I can't figure out, how can I write a ransacker that uses this scope. For example, I want this behavior:

MyModel.search(by_attr: val1) # should return MyModel.query1
MyModel.search(by_attr: val2) # should return MyModel.query2

Anyone has some thoughts about that?

Upvotes: 4

Views: 4080

Answers (2)

Nick Roz
Nick Roz

Reputation: 4230

There is an extract, from the https://github.com/activerecord-hackery/ransack/pull/288:

In your model:

scope :by_name, ->(name) {
  where name: name
}

def self.ransackable_scopes(auth_object = nil)
  [:by_name]
end

In your view (according to https://github.com/activerecord-hackery/ransack#ransacks-search_form_for-helper-replaces-form_for-for-creating-the-view-search-form):

= search_form_for @q do |f|
  = f.search_field :by_name, value, [['Value 1', val1], ['Value 2', val2]]

To avoid using explicit array while creating forms use different helpers, such as options_from_collection_for_select.

You might write MyModel.ransack(by_name: value).results in your code as well.

Upvotes: 5

Denis Tataurov
Denis Tataurov

Reputation: 193

If anybody has a problem like mine there is an interesting PR in ransack that allows to use scopes as keys in search method: https://github.com/activerecord-hackery/ransack/pull/288

Upvotes: 0

Related Questions