小编典典

ActiveRecord OR 查询

all

如何在 Rails 3 ActiveRecord 中进行 OR 查询。我发现的所有示例都只有 AND 查询。

编辑:自 Rails 5 起 OR
方法可用。参见ActiveRecord::QueryMethods


阅读 83

收藏
2022-07-06

共1个答案

小编典典

使用ARel

t = Post.arel_table

results = Post.where(
  t[:author].eq("Someone").
  or(t[:title].matches("%something%"))
)

生成的 SQL:

ree-1.8.7-2010.02 > puts Post.where(t[:author].eq("Someone").or(t[:title].matches("%something%"))).to_sql
SELECT     "posts".* FROM       "posts"  WHERE     (("posts"."author" = 'Someone' OR "posts"."title" LIKE '%something%'))
2022-07-06