It is possible to do this using the execute method, see the example:
conn = ActiveRecord::Base.connection
result = conn.execute "SELECT id, email, age FROM users LIMIT 3"
The result will be a Mysql object::Result, you can iterate this way:
Rubyresult = conn.execute "SELECT id, email, age FROM users LIMIT 2" result.each do |user| puts "id: %s" % user[0] puts "email: %s" % user[1] puts "age: %s" % user[2] puts end
Attention, take the necessary precautions not to suffer an attack through SQL Injection, can begin to avoid using quote method:
Rubyquery = "SELECT id, email, age FROM users WHERE email = %s" % conn.quote("' OR 1=1 #") puts query
# => SELECT id, email FROM users WHERE email = '\' OR 1=1 #'
You can use other methods like the select_all method. This method returns an array of hashes, with column names as index, making iteration simpler.
Rubyresult = conn.select_all "SELECT id, email FROM users LIMIT 2"
result.each do |user|
puts "id: %s" % user['id']
puts "email: %s" % user['email']
puts
end
For cases where all you need is just one line as a result, you can use the select_one method:
Rubyresult = conn.select_one("SELECT COUNT(*) AS total FROM users")
puts result['total']
In Rails, all models extend the Activerecord::Base class. Therefore, the above methods are also available in the model.
Rubyclass User < ActiveRecord::Base
def self.all
connection.select_all "SELECT id, email FROM users"
end
end
puts User.all
# => [{"id"=>"1", "email"=>"[email protected]"}, {"id"=>"2", "email"=>"[email protected]
You can do in the AR, but it’s not well for that q it is done. For your case, I would use Sequel ( http://sequel.jeremyevans.net/ )
– Alex Takitani