DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Manually Pulling Data From MySQL In Rails

  • submit to reddit
        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 ='#{}'")
    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 ='#{}'")
    return {|el| el.to_i }

There is also:

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