Rails 3 Custom SQL Queries Without Model
In Rails 3, executing custom SQL queries without using a model can be achieved by establishing a direct connection to the database. However, the code you provided encountered an issue with the execute method.
To address this, you can use the following approach:
Here's a modified version of your code that incorporates these changes:
@connection = ActiveRecord::Base.establish_connection( :adapter => "mysql2", :host => "localhost", :database => "siteconfig_development", :username => "root", :password => "root123" ) results = @connection.connection.execute("select * from users") results.each do |row| puts row[0] end
Alternatively, as suggested in the provided solution, you can also use the :as => :hash option while iterating over the results to access the columns by their names:
@connection = ActiveRecord::Base.establish_connection( :adapter => "mysql2", :host => "localhost", :database => "siteconfig_development", :username => "root", :password => "root123" ) sql = "SELECT * from users" @result = @connection.connection.execute(sql) @result.each(:as => :hash) do |row| puts row["email"] end
By using this approach, you can execute custom SQL queries directly without relying on a model.
The above is the detailed content of How to Execute Custom SQL Queries in Rails 3 Without Using a Model?. For more information, please follow other related articles on the PHP Chinese website!