[Rails Level1] MODEL & Validations
1. Model in Rails:
The reason that you use Tweet then you can find the table tweets is because:
There is a class call Tweet which extends Activerecord::Base defined by Rails,
the class maps the table tweets.
Validations:
can add validations to check the value which will be inserted into the database.
class Tweet < ActiveRecord::Base validates_presenece_of :status end
validates_presence_of will check whether the variable :status has actual value or not.
If it hasnot value, when save: it will return false
t = Tweet.new
t.save
--> false
The error message:
t.errors.messages => {status: ["can't be blank"]} t.error[:status][0] => "can't be blank"
Validations api:
Read More: http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_presence_of
validates_presence_of :status //cannot be blank validates_numericality_of :fingers //should be a number validates_uniqueness_of :toothmarks //should be uniquene validates_confirmation_of :password //for passwrod, email.. validates_acceptance_of :zombification // checkbox validates_length_of : password, minimum: 3 //longer than 3 charaters validates_format_of :email, width: /regex/i //regex format validates_inclusion_of :age, in: 21..99 //the range inside validates_exclusion_of :age, in: 0...21, message: "sorry you much be over 21"
Also, it can write in a short way:
Relationship:
Read More: http://apidock.com/rails/v4.0.2/ActiveRecord/Associations/ClassMethods/belongs_to
- has_many
a Zombie has_many Tweets
class Zombie < ActiveRecord::Base has_many :tweets end
- belongs_to
a Tweet belongs_to a Zombie
class Tweet < ActiveRecord::Base belongs_to :ombie end
Using relationships:
Now we have
1. A zombie has many tweets.
2. A tweet belongs to a zombie.
So if we want to find how many tweets a zombie has, then we can use:
//1. find the zmobie ash = Zombie.find(1) ash.tweets.count --> 3 //2. list all the tweets ash.tweets --> [id:1 .... id:4 .... id:5 ....]
Find the tweet belongs to which zombie:
//1. find the tweet t = Tweet.find(5) //2. find the zombie t.zombie //3. get the name t.zombie.name
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具