ruby on rails
After learning about Ruby, the first step we took was to understand how the web and the Ruby on Rails request-response cycle work.
了解了Ruby之后 ,我们采取的第一步是了解Web和Ruby on Rails请求-响应周期的工作方式。
Now it’s time to learn about databases and how they connect with Ruby on Rails. Basically, the answer is the Model: the M
from MVC
, as we learned here.
现在是时候了解数据库以及它们如何与Ruby on Rails连接。 基本上,答案是Model: MVC
的M
,正如我们在此处学到的。
Before learning web development with Rails, I really recommend learning about Ruby first.
在学习使用Rails进行Web开发之前,我真的建议您先学习Ruby 。
Let’s begin!
让我们开始!
Hmmm… The first thought that comes to my mind is something that stores data.
嗯……我想到的第一个想法是存储数据的东西。
But this definition is quite imprecise! An array, a hash, a linked list, or any data structure can be something that is able to store data.
但是这个定义很不精确! 数组,哈希,链表或任何数据结构都可以存储数据。
When you turn off the computer, you lose all data values that were stored in that array (the same as all data structures). So it’s not a good idea to store all my precious data
.
关闭计算机时,将丢失该阵列中存储的所有数据值(与所有数据结构相同)。 因此,存储我所有的precious data
不是一个好主意。
We need to solve two problems here:
我们需要在这里解决两个问题:
Should I store all the data in a notepad? Just put all the information inside it separated by commas, save the txt file
, and done. Now I can open it and get all the data I want. We can store data and get it anytime… problem solved!
我应该将所有数据存储在记事本中吗? 只需将所有信息放入其中,并以逗号分隔,保存txt file
,然后完成。 现在,我可以打开它并获取我想要的所有数据。 我们可以存储数据并随时获取…问题已解决!
We solved this problem, but we missed the other. Now all the data is stored and we won’t lose it. But it’s not well-structured in the file. We need the rule to store and get data in an organized and well-structured form.
我们解决了这个问题,但又错过了另一个。 现在所有数据都已存储,我们不会丢失。 但是它在文件中的结构不是很好。 我们需要规则以有组织,结构良好的形式存储和获取数据。
Let’s think about how can we organize the data in a well-structured way.
让我们考虑一下如何以一种结构良好的方式组织数据。
What about organizing all the data in tables?
如何组织表格中的所有数据?
So, here’s we have: the table’s header (columns name: First Name, Last Name, Address, etc) containing values that we’ll store. For example, if we want to store the string “Mickey” (the value), it’ll be stored in the “First Name” column.
因此,这里是:表的标题( 列名:First Name,Last Name,Address等 )包含我们将存储的值。 例如,如果我们要存储字符串“ Mickey” (值) ,则将其存储在“名字” 列中 。
Table: let’s say People
表格 :假设人
Columns: First name, Last Name, Address, etc
列 : 名 , 姓 , 地址等
Rows: in this case, we can say that a row can be a person with, for example, first name “Mickey” and last name “Mouse,” address “123 Fantasy Way,” etc.
行 :在这种情况下,我们可以说一行可以是一个人 ,例如,名字“ Mickey ”和名字“ Mouse ”,地址“ 123 Fantasy Way ”等。
Fields: all data stored in the database.
字段 :存储在数据库中的所有数据。
And now we have a well-structured way to store data: in a Table!
现在,我们有了一种结构良好的数据存储方式:在表格中!
We’ll use SQL language (I’ll not mention NoSQL world!) to manipulate the data. Let’s get the basics.
我们将使用SQL语言( 我不会提到NoSQL world! )来操纵数据。 让我们了解基础知识。
GET: if we want to get all data (person) from People table, we need to select it from that table.
GET:如果我们要从People表中获取所有数据( person ),则需要从该表中选择它。
The (*) symbol means that it will select all columns from People table. If we can get all columns, we can specify which columns we need for this select.
( *)符号表示它将从“ 人物”表中选择所有列。 如果可以获取所有列,则可以指定此选择所需的列。
2. DELETE: we want to delete all data from our People table.
2. DELETE:我们要从People表中删除所有数据。
But it’s not common to delete all data from a table. We usually use a condition to delete, like “I want to delete all people under 21 years old.” We will learn how later in this post!
但是删除表中的所有数据并不常见。 我们通常使用删除条件,例如“我要删除所有21岁以下的人。” 我们将在本文后面学习如何操作!
3. INSERT: we will insert/store data into the table.
3. 插入:我们将数据插入/存储到表中。
or we can specify into which columns we want to insert data.
或者我们可以指定要将数据插入到哪些列中。
4. UPDATE: we have stored the data, but we want to update it.
4. 更新:我们已经存储了数据,但是我们想更新它。
Now we can use SQL language to query (select, delete, insert, update) data.
现在我们可以使用SQL语言查询(选择,删除,插入,更新)数据。
But what if we want to delete just records with the last name Kinoshita?
但是,如果我们只想删除姓Kinoshita的记录,该怎么办?
Or if we want to update a specific person with first name Leandro and last name Kinoshita?
或者,如果我们要更新姓Leandro和姓Kinoshita的特定人?
Yeah, we use conditions like where and order by, and operators like or and and. Let’s see some examples:
是的,我们使用诸如where和order by的条件以及诸如or和and和的运算符。 让我们看一些例子:
Deleting all records from the people table with last name Kinoshita.
从人员表中删除姓氏Kinoshita的所有记录。
Updating all records from the people table with first name Leandro and last name Kinoshita.
更新人员表中名字为Leandro和姓Kinoshita的所有记录。
We know how to execute queries (with or without conditions). Let’s understand how the tables’ relationships work.
我们知道如何执行查询(有条件或无条件)。 让我们了解表的关系如何工作。
One to One (1–1): it’s about a relationship between two tables in which one can only belong with the other. e.g. A person has one passport and that passport belongs to that specific person. So in this example, we have table People, table Passports and a 1–1 relationship.
一对一(1-1) :关于两个表之间的关系,其中一个表只能属于另一个表。 例如,一个人只有一本护照,而该护照属于该特定人。 因此,在此示例中,我们有“人”表,“护照”表和1–1关系。
One to Many (1-n): it’s about a relationship between two tables in which a record from one table can reference many records from another. e.g. Imagine an e-commerce platform: users, orders, products, payments, etc. A user can have many orders, and each order belongs to that specific user. So in this example, we have table Users, table Orders, and a 1-n relationship.
一对多(1-n) :关于两个表之间的关系,其中一个表中的记录可以引用另一表中的许多记录。 例如,想象一下一个电子商务平台:用户,订单,产品,付款等。一个用户可以有很多订单,每个订单都属于该特定用户。 因此,在此示例中,我们具有表Users,表Orders和1-n关系。
Many to Many (n-n): it’s about a relationship between two tables in which a record from one table can reference many records from another. And a record from another can also reference many records from the one. e.g. We have again the e-commerce platform: we divide products into categories. A category has many products (category Technology has many products like cell phones, notebooks, etc) and a product can belong to many categories (product Cellphone belongs to the Technology and Electronics Categories). So in this example, we have table Products, table Categories, and an n-n relationship.
多对多(nn) :关于两个表之间的关系,其中一个表中的记录可以引用另一表中的许多记录。 另一个记录也可以引用一个记录中的许多记录。 例如,我们又有了电子商务平台:我们将产品分为几类。 类别具有许多产品(类别技术具有许多产品,例如手机,笔记本电脑等),并且产品可以属于许多类别(产品手机属于技术和电子类别)。 因此,在此示例中,我们具有表Products,表类别和nn关系。
We now understand the meaning of databases, we’ve tried some basic queries, and have talked about the relationship between tables. But how can we use that knowledge in the Ruby on Rails and web development World?
现在,我们了解了数据库的含义,我们尝试了一些基本查询,并讨论了表之间的关系。 但是,我们如何在Ruby on Rails和Web开发世界中使用这些知识呢?
First of all: Rails is Rails. The Database is Database. Is it obvious? But people usually get confused about that.
首先: Rails 是 Rails 。 数据库 是 数据库 。 明显吗? 但是人们通常对此感到困惑。
A User model can represent a Users table. But the model isn’t the table.
用户模型可以表示用户表。 但是模型不是表格。
In the database, we have tables and rows.
在数据库中 ,我们有表和行。
On rails, we have models (classes) and objects.
在rails上 ,我们有模型(类)和对象。
Imagine a blog site. The blog needs an author for each post. So we create an Authors table with some columns (first_name, last_name, etc):
想象一个博客站点。 博客的每个帖子都需要一个作者。 因此,我们创建了一个Authors表,其中包含一些列(first_name,last_name等):
In the migration, we add columns first_name
, last_name
, email
, birthday
, created_at
, and updated_at
. (created_at
and updated_at
are created by the t.timestamps
code).
在迁移中,我们添加列first_name
, last_name
, email
, birthday
, created_at
和updated_at
。 ( created_at
和updated_at
由t.timestamps
代码创建)。
So we create a migration (Ruby code), run the rake db:migrate
command in the terminal, and it generates a table Authors
with first_name
, last_name
, email
, birthday
, created_at
, and updated_at
columns.
因此,我们创建了一个迁移(Ruby代码),在终端中运行rake db:migrate
命令,它会生成具有first_name
, last_name
, email
, birthday
, created_at
和updated_at
列的Authors
表。
Back to Rails — we can create an Author
model:
返回Rails-我们可以创建一个Author
模型:
So now we have an Authors
table with some columns and an Author
model.
因此,现在我们有了一个Authors
表,其中包含一些列和一个Author
模型。
Open the terminal and type bundle exec rails c
. Remember, we are in the RAILS console, so we have classes, objects, attributes, etc.
打开终端,然后键入bundle exec rails c
。 记住,我们在RAILS控制台中,所以我们有类,对象,属性等。
We created an Authors
table/model. What we need now is a Posts
table/model. An author has many posts and a post belongs to a specific author. The relationship here is one to many (1-n). Remember?
我们创建了一个Authors
表/模型。 我们现在需要的是一个Posts
表/模型。 一个作者有很多帖子,而某个帖子属于特定作者。 这里的关系是一对多 ( 1-n )。 记得?
So when we create a Posts
table, we need to store a reference to the post’s author (column author_id in the Posts table). It’s known as the Foreign Key
.
因此,当我们创建一个Posts
表时,我们需要存储对该帖子作者的引用( Posts表中的author_id列)。 它被称为Foreign Key
。
And how do we relate the models?
以及我们如何关联模型?
has_many
帖子 (author has_many
posts)* Quick explanation about has_many
and belongs_to
. Both codes
are methods defined on ActiveRecord
class. You can see that we create our models inheriting from ActiveRecord::Base
.
*关于has_many
和belongs_to
快速说明。 这两个codes
都是在ActiveRecord
类上定义的方法。 您可以看到我们创建了从ActiveRecord::Base
继承的模型。
Remember in my Ruby Foundation article that we learned about Object Oriented Programming, the Inheritance part? This is why we can use has_many
and belongs_to
methods without defining it anywhere on our application. Rails handles it for us.
还记得我在Ruby Foundation的文章中,我们了解了面向对象编程的继承部分吗? 这就是为什么我们可以在没有在应用程序的任何位置定义has_many
和belongs_to
方法的情况下使用它的原因。 Rails为我们处理它。
If you want to understand this concept deeply, clone the Rails repo or check out the Behind the Scenes of the ‘Has Many’ Active Record Association.
如果您想深入了解这个概念,请克隆Rails回购或查看“有很多”活动记录协会的幕后花絮 。
We can query using ActiveRecord methods:
我们可以使用ActiveRecord方法进行查询:
all: Get all objects from a specific model.
all :从特定模型获取所有对象。
Behind the scenes, it is executing the SELECT * FROM posts
query.
在后台,它正在执行SELECT * FROM posts
查询。
find: Using find we can get the object by the id (primary key).
find :使用find我们可以通过id (主键)获取对象。
Behind the scenes, it is executing SELECT * FROM posts WHERE id = 1
query.
在后台,它正在执行SELECT * FROM posts WHERE id = 1
查询。
where: Get the objects that pass the conditions.
其中 :获取通过条件的对象。
Behind the scenes, it is executing SELECT * FROM posts WHERE title = 'Database & Rails'
query.
在后台,它正在执行SELECT * FROM posts WHERE title = 'Database & Rails'
查询。
order: Sort all objects based on a column.
order :基于列对所有对象排序。
Behind the scenes, it is executing SELECT * FROM posts ORDER BY created_at DESC
query.
在后台,它正在执行SELECT * FROM posts ORDER BY created_at DESC
查询。
We learned a lot here. I hope you guys appreciate the content and learn more about how the Databases and Rails models work.
我们在这里学到了很多东西。 希望大家对此内容有所了解,并了解有关数据库和Rails模型如何工作的更多信息。
This is one more step forward in my journey to learning and mastering Rails and web development. You can see the documentation of my complete journey here on my Renaissance Developer publication.
这是我学习和掌握Rails和Web开发的又一个进步。 您可以在我的Renaissance Developer出版物上看到我完整旅程的文档。
If you want a complete Ruby and Rails course, learn real-world coding skills and build projects, try One Month Ruby Bootcamp and Rails Bootcamp. See you there ☺
如果您想学习一门完整的Ruby and Rails课程,学习现实世界的编码技巧并构建项目,请尝试一个月的Ruby Bootcamp 和Rails训练营 。 在那里见you
Have fun, and keep learning and coding.
玩得开心,继续学习和编码。
My Twitter & Github. ☺
我的Twitter和Github 。 ☺
翻译自: https://www.freecodecamp.org/news/understanding-the-basics-of-ruby-on-rails-sql-databases-and-how-they-work-7a628cd42073/
ruby on rails