Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Active Record基础 #34

Open
huruji opened this issue Apr 29, 2018 · 0 comments
Open

Active Record基础 #34

huruji opened this issue Apr 29, 2018 · 0 comments
Labels

Comments

@huruji
Copy link
Owner

huruji commented Apr 29, 2018

Active Record 是MVC中的M,负责处理数据和业务逻辑,Active Record实现了Active Record模式,是一种 对象关系映射 系统

Active Record 模式:Active Record 模式: 中,对象中既有持久存储的数据,也有针对数据的操作,Active Record 模式把数据存取逻辑作为对象的一部分,处理对象的用户知道如何读写数据。

对象关系映射: ORM是一种技术手段,把应用中的对象和关系型数据库中的数据表连接起来,使用ORM,应用中对象的属性和对象之间的关系可以通过一种简单额方法从数据库中获取,无需直接编写SQL语句,也不过度依赖特定的数据库种类。

Active Record重要的功能有:

  • 表示模型和其中的数据

  • 表示模型之间的关系

  • 通过相关联的模型表示继承层次结构

  • 持久存入数据之前,验证模型

  • 以面向对象的形式操作数据库

Active Record 的约定

命名约定

Rails把模型的类名转换为复数,然后查找对应的数据表,Rails提供的单复数转换功能非常强大,类名应该使用驼峰命名:

Schema约定

  • 外键: 使用 singularized_table_name_id 形式命名,例如 item_id,order_id。创建模型关联后,Active Record 会查找这个字段。

  • 主键: 默认情况下,使用证整数字段id作为表的主键。

还有一些可选的字段:created_at、updated_at、type、lock_version

创建 Active Record 模型

只需要继承 ApplicationRecord 类就行:

class Product < ApplicationRecord
    
end

如果应用需要使用其他的命名约定,或者在 Rails 中使用已有的数据库,则可以覆盖默认的命名约定,如修改表名和主键名:

class Product < ApplicationRecord
    self.table_name = "my_products"

    self.primary_key = "product_id"
end

CRUD

创建

创建记录并存入数据库

user = User.create(name: "huruji", age: 12)

实例化,但不保存

user = User.new

调用save实例方法可以保存

user.save

使用块可以初始化对象

user = User.new do |u|
   u.name = 'huruji'
   u.age = 12
end

读取

返回所有数据

users = User.all

返回第一条数据

user = User.first

查找返回

huruji = User.find(name : 'huruji')

排序返回

users = User.where(age: 12).order(created_at: :desc)

更新

获取到Active Record对象之后,修改属性之后再保存

user = User.find_by(name: 'huruji')

user.name = 'xie'

user.save

使用update

user = User.find_by(name: 'huruji')
user.update(name: 'xie')

使用update_all批量更新数据

User.update_all "age = 12, sex = man"

删除

user = User.find_by(name: "huruji")
user.destroy

数据验证

在存入数据库之前,Active Record 可以验证模型,已检查属性值是否不为,是否唯一等。

调用 saveupdate 方法都会做数据验证,验证失败返回false。

class User < ApplicationRecord
    validates :name, presence: true
end

迁移

Rails提供了一个DSL来处理数据库模式,叫做迁移,迁移的代码储存在特定的文件中,可以通过rails命令执行。

@huruji huruji added the ruby label Apr 29, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant