2

I have a column in my table with JSON data type where I am storing an 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 is how the data is 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 and wrote a query which is working fine

SELECT *
FROM   posts, json_array_elements(edit_summary) as elem
WHERE  elem->>'date' BETWEEN '2016-08-07 00:00:00' AND '2016-08-10 23:59:59';

Now my question is there any way to do same rails way?

Community
  • 1
  • 1
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88

1 Answers1

0

You can execute the same query in Rails by providing raw SQL conditions.

However, I feel like edit summaries belong to another relation instead.

A Post has_many EditSummary, benefits:

  • you'll be able to index dates and FK's.
  • DB consistency (there's nothing preventing user_id from being a invalid id).
  • separation
  • DB validation