ransack
ransack copied to clipboard
Ransacker params with alias for Passing Arguments
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']
}]
)
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]
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."
@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
)