Rails way to query on array inside JSON data type -
i have column in table json data type storing array.
migration
class addeditsummarytoposts < activerecord::migration def change add_column :posts, :edit_summary, :json end end
post
class post < activerecord::base serialize :edit_summary, json end
this how data stored:
:id => 2, :edit_summary => [ { "user_id" => 56, "date" => "2016-08-09t07:46:04.555-04:00" }, { "user_id" => 57, "date" => "2016-08-08t06:35:44.345-04:00" }, ]
i referred this post , wrote query working fine
select * posts, json_array_elements(edit_summary) elem elem->>'date' between '2016-08-07 00:00:00' , '2016-08-10 23:59:59';
now question there way same rails way?
you can execute same query in rails providing raw sql conditions.
however, feel edit summaries belong relation instead.
a post
has_many
editsummary
, benefits:
- you'll able index dates , fk's.
- db consistency (there's nothing preventing
user_id
being invalid id). - separation
- db validation
Comments
Post a Comment