Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails ransack gem to search json column

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.

like image 697
Anbazhagan P Avatar asked Jul 09 '16 02:07

Anbazhagan P


3 Answers

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
like image 191
Mr ISH Avatar answered Nov 14 '22 03:11

Mr ISH


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
like image 26
Carlos Luis Rojas Aragonés Avatar answered Nov 14 '22 05:11

Carlos Luis Rojas Aragonés


For Rails 4.2+ (Arel 6.0+) :

  • model_name : Employee
  • column_name: extra_details (jsonb type)
  • json_key : hobbies
# 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.

like image 42
devs1993 Avatar answered Nov 14 '22 03:11

devs1993