Over a million developers have joined DZone.

Manually Pulling Data From MySQL In Rails

DZone's Guide to

Manually Pulling Data From MySQL In Rails

Free Resource
Sometimes you just have to do it yourself, like when you have relationships between different databases.
Here I wanted to retrieve an array of site_ids:

    result = ActiveRecord::Base.connection.execute("SELECT * FROM sites_users WHERE user_id ='#{self.id}'")
    rows = []
    result.each_hash {|h| rows << h['site_id'].to_i }
    return rows

UPDATE: ( An easier, better way)

    rows = ActiveRecord::Base.connection.select_values("SELECT site_id FROM sites_users WHERE user_id ='#{self.id}'")
    return rows.map {|el| el.to_i }

There is also:

select_one(sql, name = nil)
select_value(sql, name = nil)
select_all(sql, name = nil) 

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}