[英]Can't access Mysql model in rails console
我有一个现有的远程 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
当我在 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>'
任何建议我做错了什么? 我想访问我的应用程序中的远程数据库,到目前为止我还没有创建任何模型。 我需要创建所有模型吗? 我可以在我的 schema.rb 文件中看到完整的数据库结构。
为此,您可以在控制台中编写代码,例如
rails g model City
它将为您创建城市模型。 正如您所说,您已有表,因此您不需要上述语法生成的迁移。 所以你应该从 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
希望它对你有用:)
您当然可以访问mysql
数据库中的数据,但为了将其用作对象表示,您需要创建一个与数据关联的model
。
class City < ActiveRecord::Base
end
这样ActiveRecord
将为您完成艰苦的工作,以便将您的对象“链接”到数据库中的数据(假设模型名称是正确的,这里您应该有一个名为cities
的表)。
然后您将能够从 rails 控制台获取城市
City.all
有关 ActiveRecord 的更多信息,请参阅http://guides.rubyonrails.org/active_record_querying.html
如果有人遇到这种情况,请务必仔细检查您的模型。 我手动创建了它们,但忘记让 Active Record 知道我的模型。
我有:
class Currency
...
end
你需要改变这个以显示
class Currency < ApplicationRecord
...
end
可能会为您节省数小时的调试时间:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.