user10707598
user10707598

Reputation: 19

How to retrieve column data from ruby object returned from sql query?

 sql = "Select * from clients where id=1"
        records_array = ActiveRecord::Base.connection.execute(sql)
       puts(records_array.id)

I get an error if even though the query should contain an object with an id

NoMethodError (undefined method `id' for #):

Upvotes: 1

Views: 1049

Answers (2)

Dimitrius Lachi
Dimitrius Lachi

Reputation: 1287

You executing the method .id for a hash (the return of ActiveRecord::Base.connection.execute(sql)), Hashes instances don't have this method. This method will return for you a sql Result, you can access the client attriubutes executing:

records_array.first

This will return for you a array of attributes of the finded client:

[1, 'Client name', 'Client birthday']

I strongly recommend you to use a .find method from the class Client if you using ActiveRecord

Upvotes: 0

wcpaez
wcpaez

Reputation: 361

Always try to guess what method can help you. When you write record_arrays.methods it returns a list of available methods that can help you. For example, records_array.column_values(0) it is going to return all values from the first column, in this case maybe the list of all client ids, another method is records_array.values. You can check what method can help you.

Upvotes: 0

Related Questions