Search code examples
ruby-on-railspostgresqlhstore

Accessing HSTORE data in rails controller


So I set up a postgres server and have it working with hstore values.

As of right now, I have a table books, structured with

name:string data:hstore

I have created a sample entry to test:

Book.create(:name => "My First Book", :data => {'author' => 'Kevin', 'pages' => 368})

I have loaded the data into a variable:

@book = Book.where("data ? :key", :key => 'pages')

(just to test, i realize this query would serve no real purpose...)

I print the data as JSON and this works fine, the entry is found and displayed. However, what I am trying to do is access, say the pages, an hstore value. I did some research and found

@book.data['pages']

However, when i try to run this, I get

undefined method `data' for #<Book::ActiveRecord....

Any and all help is greatly appreciated!


Solution

  • The Active Record where will give you an array even if there is only 1 value.

    You can do

    @book = Book.where("data ? :key", :key => 'pages')[0]
    

    to get that record

    and then

    @book.data
    

    will work as desired.

    If you might get multiple records and just using the first found is ok you could also use:

    @book = Book.where("data ? :key", :key => 'pages').first
    @book.data
    

    or just

    @book = Book.where("data ? :key", :key => 'pages').first.data