ransack icon indicating copy to clipboard operation
ransack copied to clipboard

Ransacker params with alias for Passing Arguments

Open psoldier-robly opened this issue 5 years ago • 3 comments

In 6. Passing arguments to a ransacker

The example to call a ransacker has full-name params

Person.ransack(
  conditions: [{
    attributes: {
      '0' => {
        name: 'author_max_title_of_article_where_body_length_between',
        ransacker_args: [10, 100]
      }
    },
    predicate_name: 'cont',
    values: ['Ransackers can take arguments']
  }]
)

:attributes, :predicate_name, :values don't work, it should be :a, :p, :v

Person.ransack(
  conditions: [{
    a: {
      '0' => {
        name: 'author_max_title_of_article_where_body_length_between',
        ransacker_args: [10, 100]
      }
    },
    p: 'cont',
    v: ['Ransackers can take arguments']
  }]
)

psoldier-robly avatar Mar 11 '19 11:03 psoldier-robly

Could you please explain why is that?

I created my own ransacked method in model, and now I try to pass args there. I also need to merge these params with params[:q]

mateuszbialowas avatar Sep 08 '23 09:09 mateuszbialowas

I confirm that you need to use the alias methods :a, :p, :v instead of the original methods :attributes, :predicate_name, :values if you want to use the conditions argument."

m3thom avatar Jan 03 '24 06:01 m3thom

@mateuszbialowas

You could do something like this.

# Assuming your `params[:q]`
# puts params[:q]
# {"id_eq": 1, title_eq: "Input title"}
  • Option 1: Inject your ransacked method into params[:q]
if some_condition_or_inject_directly
  params[:q][:conditions] = [{
    a: {
      '0' => {
        name: 'author_max_title_of_article_where_body_length_between',
        ransacker_args: [10, 100]
      }
    },
    p: 'cont',
    v: ['Ransackers can take arguments']
  }]
end
  • Option 2: Use the spread operator
Person.ransack(
  conditions: [{
    a: {
      '0' => {
        name: 'author_max_title_of_article_where_body_length_between',
        ransacker_args: [10, 100]
      }
    },
    p: 'cont',
    v: ['Ransackers can take arguments']
  }],
  **params[:q] # Spread the rest of the search, and it will be merged automatically by ransacker
)

m3thom avatar Jan 03 '24 06:01 m3thom