生成一个使用数据库中预先存在的数据的模型 [英] Generate a model that uses pre-existing data from database

查看:81
本文介绍了生成一个使用数据库中预先存在的数据的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用预先存在的数据库制作应用程序,我将database.yml设置为使用该数据库。

Im making an application with a pre-existing database, I set up the database.yml to use the database.

database.yml

   development:
  adapter: mysql2
  encoding: utf8
 # database: ttlem_demo_development
  database: ttle
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: mysql2
  encoding: utf8
  database: ttlem_demo_test
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

production:
  adapter: mysql2
  encoding: utf8
  database: ttlem_demo_production
  pool: 5
  username: root
  password:
  socket: /tmp/mysql.sock

我只希望从数据库中取出一张表,称为帐户视图,我尝试为此生成一个具有所有正确字段的支架,但它告诉我,如果我进行迁移,则需要迁移(在浏览器中呈现时)我将无法使用现有数据,这正确吗?我如何制作一个将使用现有数据和字段的模型?

I only want one table out of the database it is called account views, I try to generate a scaffold for this with all the correct fields but it tells me i need to migrate (when i render it in the browser), if i migrate i wont be able to use the existing data, is this correct? How can i make a model that will use the existing data and fields?

谢谢您的所有帮助:)

Thank you for all your help :)

推荐答案

两件事尝试:...
#1在不进行迁移的情况下运行您的脚手架,因此它不认为您缺少其中一个。

Two things to try:... #1 Run your scaffold without a migration so it doesn't think you're missing one.

rails g scaffold yourmodelname fieldone:fieldtype ... etc  --no-migration

# 2如果这不起作用,则可以进行很多工作,但可以使用有效的架构版本号进行转储和重新加载

#2 If that doesn't work you can go the long way round but dumping and reloading with a valid schema version number

将此数据库yml添加到您的gemfile中:

Add this db to yml to your gemfile:

gem 'yaml_db', github: 'jetthoughts/yaml_db', ref: 'fb4b6bd7e12de3cffa93e0a298a1e5253d7e92ba'

它适用于rails 3或rails 4。

It works for either rails 3 or rails 4.

对您的架构进行转储当前数据库,因此您将获得一个带有有效版本号的schema.rb。

Do a schema dump of your current database so you'll get a schema.rb with a valid version number.

bundle exec rake db:schema:dump

现在您已经有了一个有效的架构来转储数据。

Now that you have a valid schema dump your data.

 bundle exec rake db:data:dump

删除数据库(如果愿意,可以使用mysql命令手动进行操作,或者运行rake db:drop)

Drop your database (you can do it manually using the mysql commands if you prefer or run rake db:drop)

现在用您的模式文件重新创建它。

Now recreate it with your schema file.

 bundle exec rake db:schema:load

现在添加回您的数据

bundle exec rake db:data:load

启动服务器,并假设您正确匹配了模型中的所有数据字段(因此从支架中设置了适当的强参数),您应该会很好。

Start your server and assuming your correctly matched all your data fields in your model (so the proper strong parameters are set from your scaffold) you should be good.

这篇关于生成一个使用数据库中预先存在的数据的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆