Rails 3在没有模型的情况下执行自定义sql查询

nee*_*raj 104 sql ruby-on-rails

我需要编写一个独立的ruby脚本来处理数据库.我在rails 3中使用了下面给出的代码

@connection = ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
:database => "siteconfig_development",
:username => "root",
:password => "root123"
)

results = @connection.execute("select * from users")
results.each do |row|
puts row[0]
end
Run Code Online (Sandbox Code Playgroud)

但得到错误: -

`<main>': undefined method `execute' for #<ActiveRecord::ConnectionAdapters::ConnectionPool:0x00000002867548> (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

我在这里失踪了什么?

从denis-bu获得解决方案后,我按照以下方式使用它,这也有效.

@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
Run Code Online (Sandbox Code Playgroud)

den*_*-bu 167

也许试试这个:

ActiveRecord::Base.establish_connection(...)
ActiveRecord::Base.connection.execute(...)
Run Code Online (Sandbox Code Playgroud)

  • FWIW,使用空参数不是惯用的红宝石.所以做`connection.execute`而不是`connection().execute` (14认同)

Sac*_*n R 100

connection = ActiveRecord::Base.connection
connection.execute("SQL query") 
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`ActiveRecord :: Base.connection.execute("SQL查询")` (16认同)
  • 在这种情况下,connection = ActiveRecord :: Base.connection; connection.execute("SQL查询")可以工作.减少打字! (8认同)
  • 之后可能必须将此连接返回到连接池以避免线程问题:`ActiveRecord :: Base.connection_pool.checkin(connection)`http://apidock.com/rails/ActiveRecord/ConnectionAdapters/ConnectionPool (3认同)

haj*_*poj 35

我建议使用ActiveRecord::Base.connection.exec_query而不是ActiveRecord::Base.connection.execute返回一个ActiveRecord::Result(在rails 3.1+中可用),它更容易使用.

然后你就可以访问它在不同的结果以各种方式类似.rows,.each.to_hash

来自文档:

result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts')
result # => #<ActiveRecord::Result:0xdeadbeef>


# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end
Run Code Online (Sandbox Code Playgroud)

注意:从这里复制我的答案


mon*_*ike 24

您也可以使用find_by_sql

# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
Run Code Online (Sandbox Code Playgroud)

  • 你是对的,我太快读了你的问题.这个答案可能会帮助根据您的问题标题访问此页面的其他人. (4认同)