ruby-on-railsjsonahoy

find_by() in json data


I am using ahoy gem for analytics. In the ahoy_events table, I have properties column of json data type. I want to find specific data based on that column.

Suppose I have

{"tag":"a","class":"bigyapan-6","page":"/client/dashboard","text":"","href":"http://www.google.com"}

this as data and I want to find_by class.

In the rails c I ran Ahoy::Event.find_by(properties[:class]: "bigyapan-6") and it gave me an err

Ahoy::Event.find_by(properties["class"]: "bigyapan-6")
SyntaxError: unexpected ')', expecting end-of-input

Solution

  • This is a syntax error since properties[:class] is not a valid hash key in Ruby. To query Postgres JSON columns you need to provide the query as a string:

    Ahoy::Event.find_by("properties ->> 'class' = 'bigyapan-6'")
    

    ActiveRecord does not take a nested hash in this case like it would for an association. I doubt that ActiveRecord will ever support this since its very RBDMS specific and the type coercion thing (-> vs ->>) would make it really complex.

    # this won't work.
    Ahoy::Event.find_by(properties: { class: 'bigyapan-6' })
    

    See: