0

我正在为 ActiveRecord 生成条件,如下所示:

  query = {:status => status}

  if (limit)
    query[:limit] = @vals['limit'].to_i
  end

  if (offset && limit)
    query[:offset] = (offset - 1) * limit
  end

  rows = Review.all(query)

这工作得很好。我过滤评论的“状态”,如果传入,我会填写限制和偏移量。问题是现在我需要在评论内容字段上添加“非空”检查。IE AND review.content != '' && review.content != nil

我读过你可以做类似的事情

Review.were("review <> ''")

这本身就可以工作,但我不确定如何将其合并到我的上述命令中。或者更改上述命令以使用 where 语句而不是“all”语句。

4

1 回答 1

2

我会写这样的代码

query = Review.where("status = ?", status).where("review <> '' AND review IS NOT NULL")

if limit.present?
  query = query.limit(limit) 
  if offset.present?
    query = query.offset((offset - 1) * limit)
  end
end

rows = query.all

rails 查询对象进行惰性评估,因此您可以构建查询,在开始迭代行之前不会向数据库发出 sql

交替.where("review <> '' AND review IS NOT NULL")

.where("COALESCE(review, '') <> ''")

于 2013-03-23T19:35:50.123 回答