Can I use activerecord for basic queries? No mapping?

Asked

Viewed 42 times

1

I do automated testing of a large system, need to validate many tables in different databases. I’m thinking of using Active Record, but all the examples I’ve seen in research show that the tables to be used are mapped first and used as a model. Is there any way to use Active Record without mapping in some cases? If so, what are they? I am currently using OCI8

If for a simple validation of this I map each table will be very time consuming, the gains are really so high?

  • 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/ )

1 answer

0


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]
  • Ahhhh, thank you very much!! Really, that’s what I was trying to understand if it was possible to do!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.