NullVoxPopuli
NullVoxPopuli

Reputation: 65173

Ruby on Rails 2.3.8: How do I do a custom SQL query, returned as an object / ActiveRecord object, rather than a hash?

Le code:

ActiveRecord::Base.connection.select_all("Le Query")

The above will return a hash formatted as such:

{"name"=>"title", "sequence"=>"0", "body"=>"", "section_id"=>"74", "id"=>"325", "revision"=>"2"}

Now, normally, if just do ModelName.find(conditions), i'll get something like the following:

#<ObjectName id: 272, name: "title", body: "", sequence: 0, section_id: 89, revision: 0>

Now, is there a way to convert the hash to a format such that if the hash is stored in variable "a", I could do something like:

a.name

like it was an active record object, rather than

a["name"] 

as I do currently with the above hash

Upvotes: 1

Views: 466

Answers (2)

Wizard of Ogz
Wizard of Ogz

Reputation: 12643

MyModel.find_by_sql("Le Query")

Upvotes: 3

Jeff Paquette
Jeff Paquette

Reputation: 7127

Did you try something like this?

a = ModelName.new(ActiveRecord::Base.connection.select_all("Le Query"))

Upvotes: 0

Related Questions