I have a field as json column and i have to search all the phone values inside that column, i have searched for it and i have not found any document using ransack. Is it possible to use ransaack to search json column? I have used the ransack to search other fields, so i have to use ransack or something that can combine both result
my json column looks like this
{"phone1"=>"", "relationship_type1"=>"", "relationship_name1"=>"", "phone2"=>"", "relationship_type2"=>"", "relationship_name2"=>"", "phone3"=>"", "relationship_type3"=>"", "relationship_name3"=>"", "phone4"=>"", "relationship_type4"=>"", "relationship_name4"=>""}
phone1, phone2,3,4 should be searcheable.
See the Ransack wiki
For each JSON column add one of these to your model, and it will enable your JSON column to be ransacked as normal columns:
ransacker :phone1 do |parent|
Arel::Nodes::InfixOperation.new('->', parent.table[:json_column], 'phone1')
end
Having a table with a json column called properties
, you should be able to tell ransack
to look inside the phone1 with the following snippet:
ransacker :phone1 do
Arel.sql("table.properties ->> 'phone1'")
end
For Rails 4.2+ (Arel 6.0+) :
# in models/employee.rb
ransacker :hobbies do |parent|
Arel::Nodes::InfixOperation.new('->>', parent.table[:extra_details], Arel::Nodes.build_quoted('hobbies'))
end
Test it console :
Employee.search({ "hobbies_cont" => "Reading" }).result
# or
Employee.ransack({ "hobbies_cont" => "Painting" }).result
both search & ransack work. search will be deprecated in the next major version of Ransack.
->
does not work as intended. ->>
works.
Ransack Wiki.
Blog/tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With