继续:Ruby on Rails 简单了解

一. 接着上一篇继续

1.限制微博的长度

在 Rails 中实现这种限制很简单,使用验证(validation)功能即可。要限制微博的长度最多为 140 个字符

(1).打开文件:app/models/micropost.rb

class Micropost < ApplicationRecord

  validates :content, length: {maximum: 140}

end

注:这句话的具体意思,稍后再谈,反正猜也能猜出来

(2).然后,看效果:

2.建立关联(一个用户拥有多篇微博, 一篇微博属于一个用户)

(1).打开文件:app/models/user.rb

class User < ApplicationRecord
  has_many :microposts
end

(2).打开文件:app/models/micropost.rb

class Micropost < ApplicationRecord
  belongs_to :user
  validates :content, length: {maximum: 140}
end

关联关系:

(3).穿插个知识点,记住了!!知识点!!!

在控制台打印第一个用户所对应的微博

# 解释一下
rails console:打开rails的控制台输出
exit:退出控制台
注:中间啥意思,自己猜

3.限制字段不能为空

(1).打开文件:app/models/user.rb

class User < ApplicationRecord
  has_many :microposts
  validates :name, presence: true
  validates :email, presence: true
end

(2).打开文件:app/models/micropost.rb

class Micropost < ApplicationRecord
  belongs_to :user
  validates :content, length: {maximum: 140}, presence: true
end

注:自己试一下

4.简单了解一下Ruby的继承体系

(1).User类和Mcropost类

# User 类的继承关系:
class User < ApplicationRecord
...
end

# Mcropost 类的继承关系:
class Micropost < ApplicationRecord
...
end

注:可以看出, User 和 Micropost 都(通过 < 符号)继承自 ApplicationRecord 类,而这个类继承自 ActiveRecord::Base 类,这是 Active Record 为模型提供的基类。图中列出了这种继承关系。继承 ActiveRecord::Base 类,模型对象才能与数据库通讯,才能把数据库中的列看做 Ruby 中的属性,等等。

(2).UsersController类和MicropostsController类

# UsersController 类中的继承
class UsersController < ApplicationController
...
end

# MicropostsController 类中的继承
class MicropostsController < ApplicationController
...
end

# ApplicationController 类中的继承
class ApplicationController < ActionController::Base
...
end

注:控制器的继承结构与模型基本相同。可以看出, UsersController 和 MicropostsController 都继承自 ApplicationController 。如代码所示, ApplicationController 继承自ActionController::Base 。 ActionController::Base 是 Rails 中 Action Pack 库为控制器提供的基类。

。。。

简单了解,已经结束了,接下来该正式学习了

原文地址:https://www.cnblogs.com/rixian/p/11654325.html