Ari*_*dha 3 ruby-on-rails rails-console ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2
我有一个现有的远程 mysql 数据库,我正在尝试从我的 rails 应用程序访问它,我的 database.yml 开发中有这个:
development:
adapter: mysql2
encoding: utf8
database: mydb
username: myusername
password: !@#$%@!
host: IP for my DB
port: 3306
pool: 5
socket: /tmp/mysql.sock
timeout: 5000
Run Code Online (Sandbox Code Playgroud)
当我在 Rails 控制台中运行以下命令时
ActiveRecord::Base.connection.tables
它列出了所有可用的表,但是当我尝试访问模型时,它给了我以下错误:
City
NameError: uninitialized constant City from (irb):12
from /home/shreyas/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands/console.rb:47:in `start'
from /home/shreyas/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands/console.rb:8:in `start'
from /home/shreyas/.rvm/gems/ruby-1.9.3-p194/gems/railties-3.2.11/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Run Code Online (Sandbox Code Playgroud)
任何建议我做错了什么?我想访问我的应用程序中的远程数据库,到目前为止我还没有创建任何模型。我需要创建所有模型吗?我可以在我的 schema.rb 文件中看到完整的数据库结构。
为此,您可以在控制台中编写代码,例如
rails g model City
Run Code Online (Sandbox Code Playgroud)
它将为您创建城市模型。正如您所说,您已有表,因此您不需要上述语法生成的迁移。所以你应该从 db/migrate 中删除生成的迁移。
否则你可以做一件事,只需在 app/models 中添加 city.rb 文件。然后添加代码
class City < ActiveRecord::Base
# if your table name is cities, then you don't need to do any thing.
# if your table name is something else rather than cities then place the following commented code
# self.table_name = 'your_existing_city_table_name'
# then you have to add columns of the table as attr_accessible. for e.g. you have name, state_id in there
attr_accessible :name, :state_id
end
Run Code Online (Sandbox Code Playgroud)
希望它对你有用:)
| 归档时间: |
|
| 查看次数: |
2118 次 |
| 最近记录: |