0

这段代码到底有什么问题?以及如何运行这段代码?由于我是红宝石新手,请彻底解释一下。请帮忙!!!

my_connection_base.rb

类 MyConnectionBase < ActiveRecord::Base

client = Mysql2::Client.new(:host => "localhost", :database => "flipkart_project_development", :table => "users" , :username => "flipkart_project", :password => "mypass")

结果 = client.query("SELECT * FROM users")

把结果

结尾

4

2 回答 2

0

给定的代码很难按需执行:它将在加载模型时执行。它应该放在一个方法中:

class MyConnectionBase < ActiveRecord::Base   
  def some_method
    client = Mysql2::Client.new(:host => "localhost", :database => "flipkart_project_development", :table => "users" , :username => "flipkart_project", :password => "mypass")
    results = client.query("SELECT * FROM users")
    puts results
  end
end

然后可以在您的控制器中使用MyConnectionBase.some_method. 但是你为什么要这样做,我完全不知道。用 Rails 的方式来做会更好(见我上面的评论)。

于 2012-07-30T12:28:46.693 回答
0

在 Rails 中,您不需要编写原始 SQL 查询。

只需将所有数据库配置放在 config/database.yml 文件中,如下所示。

development:
  adapter: mysql2
  database: flipkart_project_development
  username: flipkart_project
  password: yourpass
  pool: 5
  timeout: 5000
test:
  adapter: mysql2
  database: flipkart_project_test
  username: flipkart_project
  password: yourpass
  pool: 5
  timeout: 5000

production:
  adapter: mysql2
  database: flipkart_project_production
  username: flipkart_project
  password: yourpass
  pool: 5
  timeout: 5000

Rails 将负责建立连接和执行查询。

在您的情况下,生成一个名为 user 的模型

 rails g model user

在您的项目中,您可以获取所有用户,如下所示。

User.all
#This will generate the SQL query "select * from users" 
#and will return the records as user objects.

也看看迁移

于 2012-07-30T10:30:01.867 回答