Rails 数据库学习笔记

本文介绍如何在Rails项目中实现多个数据库的连接,并详细解释了如何通过简单的配置让特定Model连接到指定数据库。此外,还介绍了Rails Model的基本操作命令,包括创建、修改和删除字段的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

大家都知道Rails框架的强大、简单和优雅,所以闲话不多说,总结一下最近学习到用到的Rails在数据库上的一些基本操作方法。


1. 在Rails项目中实现多个数据库的连接

在rails项目中通常会设置development、test和production三种环境,分别对应我们开发、测试和正式的三种环境。

在项目的数据库配置中通常也会设置三种环境下的数据库连接,如在我们的database.yml中:

development:
  adapter: mysql2
  encoding: utf8
  host: localhost
  reconnect: false
  database: devlopment
  username: root
  password: mysql

test:
  adapter:......

production:
  adapter:.......

但在开发过程中如果需要用到其他数据库,如another_db中的数据,只需这样:

another_db:

  adapter: mysql2
  encoding: utf8
  host: localhost
  reconnect: false
  database: another
  username: root
  password: mysql

假设在项目中有一个叫做user的model需要连接到这个数据库,那么除了像这样的初始化:

#RAILSROOT/app/models/user.rb

class User < ActiveRecord::Base 
end

需要增加这样一行代码:

establish_connection :another_db

我们的user model的增删改查等操作都会作用到another_db上

2. Rails model 操作命令

新建model:

Rails g model ModelName  Field1:field_type   Field2:field_type    Field3:field_type    Field4:field_type......

在已有的model中添加新的field:

rails generate migration AddColumeToTable colume:type

删除model中已有的field:

rails generate migration RemoveColumeFromTable colume:type

重命名model中的某个field,如将某个model中的某列point重命名为points,则首先使用:

rails g RenamePointToPoints

生成一个类似20****_rename_point_to_points.rb的文件,然后分别在up和down方法中作如下处理:

class RenamePointToPoints < ActiveRecord::Migration
  def up
  	rename_column :model_name, :point, :points
  end

  def down
  	rename_column :model_name, :points, :point
  end
end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值