1.获取单个数据
在 Active Record 中获取单个对象有好几种方法
1.1 使用主键
使用 Model.find(primary_key)
方法可以获取指定主键对应的对象
代码
# Find the client with primary key (id) 10.
client = Client.find(10)
# => #<Client id: 10, first_name: "Ryan">
1.2 take
Model.take
方法会获取一个记录,不考虑任何顺序
代码
client = Client.take
# => #<Client id: 1, first_name: "Lifo">
1.3 first
Model.first
获取按主键排序得到的第一个记录
代码
client = Client.first
# => #<Client id: 1, first_name: "Lifo">
1.4 last
Model.last
获取按主键排序得到的最后一个记录
代码
client = Client.last
# => #<Client id: 221, first_name: "Russel">
1.5 find_by
Model.find_by
获取满足条件的第一个记录
代码
Client.find_by first_name: 'Lifo'
# => #<Client id: 1, first_name: "Lifo">
Client.find_by first_name: 'Jon'
# => nil