Rails查询接口 #

一、基本查询 #

1.1 查找方法 #

ruby
# 查找单个
User.find(1)
User.find_by(email: 'john@example.com')
User.first
User.last
User.take

# 查找多个
User.find([1, 2, 3])
User.where(name: 'John')

二、条件查询 #

2.1 where条件 #

ruby
# 等于
User.where(name: 'John')

# 范围
User.where(age: 18..30)

# 数组
User.where(name: ['John', 'Jane'])

# LIKE
User.where('name LIKE ?', '%John%')

# 多条件
User.where(name: 'John').where(age: 18..30)

三、排序和分页 #

3.1 排序 #

ruby
User.order(created_at: :desc)
User.order(name: :asc, created_at: :desc)

3.2 分页 #

ruby
User.limit(10)
User.limit(10).offset(20)

# 使用kaminari
User.page(params[:page]).per(20)

四、关联预加载 #

4.1 includes #

ruby
# 避免N+1查询
users = User.includes(:articles).all
users.each { |user| user.articles }

4.2 joins #

ruby
User.joins(:articles).where(articles: { status: 'published' })

五、作用域 #

5.1 定义作用域 #

ruby
class Article < ApplicationRecord
  scope :published, -> { where(status: 'published') }
  scope :recent, -> { order(created_at: :desc) }
  scope :by_user, ->(user) { where(user: user) }
end

# 使用
Article.published.recent
Article.by_user(current_user)

六、总结 #

6.1 核心要点 #

要点 说明
find 查找单个
where 条件查询
order 排序
includes 预加载
scope 作用域

6.2 下一步 #

现在你已经掌握了查询接口,接下来让我们学习 回调机制,深入了解Rails的模型回调!

最后更新:2026-03-28