Lax*_*Sam 2 ruby ruby-on-rails-4
我正在尝试为搜索查询编写逻辑。有许多具有不同参数的不同条件。表单发送的一个参数是code。因此,code在两个不同的表中有值:competitions和responses。我需要params[:code]首先在competitions表中检查该值,如果不存在,则在responses表中检查。如果在任何一个表中都不存在,则应返回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] }))
Run Code Online (Sandbox Code Playgroud)
上面的代码仅检查的值competitions.where(code: params[:code])。如果该值为[],则它不评估第二个条件。为了按照上述要求工作,上述代码应该做哪些更改?
competitions.where(code: params[:code])返回一个Relation总是真实的对象。
幸运的是,它实现了#presencemethod,如果不为空,则返回值nil。因此,这应该工作:
competitions.where(code: params[:code]).presence || ...
Run Code Online (Sandbox Code Playgroud)