A. Then continue on a
1. The length of the limitation Twitter
This limitation in Rails achieve very simple to use verification (Validation) function. To limit the microblogging length of up to 140 characters
. (1) open file: app / models / micropost.rb
class Micropost < ApplicationRecord validates :content, length: {maximum: 140} end
Note: The specific meaning of this sentence Talk to you later, anyway, guess can guess
. (2) Then, to see the effect of:
2. association (a user has many articles Weibo, a microblogging belong to a user)
. (1) open file: app / models / user.rb
class User < ApplicationRecord has_many :microposts end
. (2) Open the file: app / models / micropost.rb
class Micropost < ApplicationRecord belongs_to :user validates :content, length: {maximum: 140} end
connection relation:
(3). Interspersed knowledge points, remember! ! Knowledge points! ! !
Printing a first user console corresponding Twitter
# Explain rails console: Open the rails console output exit: exit the console Note: Middle What do you mean, guess yourself
3. Restrictions field can not be empty
. (1) open file: app / models / user.rb
class User < ApplicationRecord has_many :microposts validates :name, presence: true validates :email, presence: true end
. (2) Open the file: app / models / micropost.rb
class Micropost < ApplicationRecord belongs_to :user validates :content, length: {maximum: 140}, presence: true end
Note: try their own
4. A quick look at the inheritance hierarchy Ruby
(1) .User classes and class Mcropost
# Inheritance User class: class User < ApplicationRecord ... End # inheritance Mcropost class: class micropost < ApplicationRecord ... End
NOTE: It can be seen, User, and Micropost ApplicationRecord inherit from classes (by <symbol), and this class inherits from ActiveRecord :: Base class, which is the base class for the model provides the Active Record. This figure shows the inheritance relationship. ActiveRecord :: Base class inheritance, model objects to communicate with the database, the database columns can be seen as Ruby in the property, and so on.
(2) .UsersController classes and class MicropostsController
# UsersController class inherits class UsersController < ApplicationController ... End # inherit MicropostsController class class MicropostsController < ApplicationController ... End # ApplicationController class inherits class ApplicationController < ActionController :: Base ... End
Note: the controller model inheritance structure is substantially the same. As can be seen, UsersController and MicropostsController inherit from ApplicationController. As shown in the code, ApplicationController inherits from ActionController :: Base. ActionController :: Base is the base class in Action Pack Rails library provided by the controller.
。。。
Simple to understand, it is over, the next formal learning