Ruby学习——数据库操作

配置数据库

数据库连接,与asp.net类似,同样使用配置文件来实现,在这里我们可以方便对数据库连接进行配置。

 config=》database.yml文件,可以找到类似的代码,这就是最基本的数据库配置,其实,在ASP.NET就相当于配置文件中的链接数据库的字符串。

development:
  adapter: mysql
  encoding: utf8
  database: Test_development
  username: root
  password: sa
  host: localhost

adapter:告诉Rails当前使用的数据库类型
database参数用于指定数据库名称
username和password参数用于登录数据库
host:告诉Rails,数据库在哪台机器运行,大部分在本定,则指定为localhost.

数据库迁移任务(database migration)

每个迁移任务代表针对数据库进行的一次修改,采用独立于数据库的源程序形式来描述。修改的内容既可能是针对数据库结构的,也可能是针对表中的数据的。你可以用这些迁移任务来升级数据库,也可以撤销它们的作用。  

创建数据库

右击项目,选择“运行/调试rake任务”,在过滤器中输入db:create,选择创建任务,双击直接运行,便可创建数据库。

 rake db:create 

创建数据表

ruby script/generate migration add_table  

定义migration

Code
class AddTable < ActiveRecord::Migration
    def self
.up
create_table 
:people do |t|
      
# id字段会自动添加
      t.column :name,    :string, :limit => 50, :null => false
      t
.column :city,    :string, :limit => 70, :null => false
      t
.column :state,   :string, :limit => 2,  :null => false
      t
.column :zip,     :string, :limit => 10, :null => false 
    end
  end

  def self
.down
    drop_table 
:people
  end
end 

up()方法用于实施迁移,而down()方法用于撤销up()的方法。

注:数据表中会自动创建一个主键(ID)字段,除非你要自定义一个ID字段,否则你不用指定它。默认的字段还有created_at 和updated_at。

合法的字段类型有以下这些: binary, boolean, date, datetime, decimal, float, integer, string, time, 以及 timestamp。

可用的选项有:limit, default, and null. 比方说 :null => false 用来指定该字段不能为空。这非常容易理解。

右击项目-》迁移数据库-》至当前版本

修改数据表

添加字段

alter table products add price decimal(8,2) default 0 not null

alter table products drop column price

class AddPriceToProduct < ActiveRecord::Migration
  def self.up
    add_column :products, :price, :decimal, :precision => 8, :scale => 2, :default => 0, :null => false
  end

  def self.down
    remove_column :products, :price
  end
end

添加索引

    #这里索引名称为 index +_+ 表名 +_+ 字段名
    add_index :ranks, ["user_id"], :name => "index_ranks_user_id"

原文地址:https://www.cnblogs.com/yank/p/1413604.html