使用 || 为变量赋值Ruby 中带有 if 条件的运算符

Assign value to a variable using || operator with if condition in Ruby

我正在尝试为搜索查询编写逻辑。有许多具有不同参数的不同条件。从表单发送的一个参数是code。所以在两个不同的 table 中有 code 个值:competitionsresponses。我需要的是首先检查 competitions table 中的 params[:code] 值,如果它不存在则检查 responses table。如果它在 table 中都不存在,那么它应该 return nil。我试图将它写在一个 if 语句中。我试过的代码如下:

competitions = Competition.includes(:event, :responses)
if params[:code].present?
  competitions = (competitions.where(code: params[:code])) || 
  (competitions.joins(:responses).where(responses: { code: params[:code] }))

以上代码只检查competitions.where(code: params[:code])的值。如果该值为 [],则它不会评估第二个条件。我应该做哪些更改才能使上述代码按照上述要求工作?

competitions.where(code: params[:code]) returns 始终为真值的 Relation 对象。

幸运的是,它实现了 #presence 方法,如果不为空则返回值,或者 nil。所以,这应该有效:

competitions.where(code: params[:code]).presence || ...