How to use SQL without a model?

I want to do a SQL query, but I haven’t created a model. For example,
instead of Car.find(:all) I want to be able to use SELECT * from cars. I
don’t have a Car model because this DB was not created with Rails (it’s
from a PHP project).

I don’t know, if that’s the best way to do it,
since I nearly never had to use it that way.
For most cases Model.find_by_sql was enough, but
that requires at least a very basic model.

But you can run plain SQL like this:

@foo = ActiveRecord::Base::connection.execute(“SELECT ALL * FROM
cars”)
and then @foo.each will give you all the data.

@foo is of class Mysql::Result
I don’t know, what the methods are that this class has,
but @foo.methods will give you a list and maybe
you can find something useful

On Jun 19, 5:30 pm, Thorsten Müller [email protected] wrote:

@foo is of class Mysql::Result

if you use select_all then you get an array of hashes which is
probably easier to play with.

Fred

I do this in a rails app of mine. I just set up regular ruby classes
to handle it (not inherited from Active Record). Just because you’re
using rails doesn’t mean you always have to use Active Record.

On Jun 19, 12:46 pm, John S. [email protected]

John S. wrote:

I want to do a SQL query, but I haven’t created a model. For example,
instead of Car.find(:all) I want to be able to use SELECT * from cars. I
don’t have a Car model because this DB was not created with Rails (it’s
from a PHP project).

Also I want to use a different database when I use this SQL queries. I
mean, is a Ruby app, but uses this SQL queries to access to a different
database.

class Crm < ActiveRecord::Base
end
class Connection1 < Crm
self.establish_connection(:adapter => “mysql”,:username => ‘blah’,
:password =>
‘badpassword’,:host=>‘localhost’,:database=>‘test_development’)
end
class Connection2 < Crm
self.establish_connection(:adapter => “mysql”,:username => ‘blah’,
:password =>
‘badpassword’,:host=>‘localhost’,:database=>‘test_development’)
end

def self.method_missing(method,*args)
if Crm::ALL.include? method.to_s.classify
eval(method.to_s.classify)
else
super
end
end

puts Crm.send(:connection1).find_by_sql(“blah”)
puts Crm.send(:connection2).find_by_sql(“blah”)

You can have as many “connections” as you like.
Depending on file placement, you may need to preload the top CRM class
as rails is loading.

John S. wrote:

John S. wrote:

I want to do a SQL query, but I haven’t created a model. For example,
instead of Car.find(:all) I want to be able to use SELECT * from cars. I
don’t have a Car model because this DB was not created with Rails (it’s
from a PHP project).

Also I want to use a different database when I use this SQL queries. I
mean, is a Ruby app, but uses this SQL queries to access to a different
database.

David H. wrote:

So I only need to create this class, into the model folder, isn’t it?
Thanks, I will try it.