在更高级的查询中,通过多个ID搜索Rails模型的正确方法是什么?

时间:2017-05-09 19:17:59

标签: ruby-on-rails postgresql select model ruby-on-rails-5

我使用的是Rails 5和PostGres 9.5。如何编写基于查找多个ID返回结果的Rails查询?我有这个

    criteria = "my_objects.id IN ?"
    param = "(#{params[:ids]})"
...
  @results = MyObject.joins("LEFT OUTER JOIN addresses ON my_objects.address_id = addresses.id")
                 .where("#{criteria} AND EXISTS (SELECT * FROM my_object_times WHERE my_object_times.my_object_id = my_objects.id)", param)
                 .order(order_by)
                 .paginate(:page => params[:page])

ID通过查询字符串参数传入,taht看起来像

ids=9e24abc1-1422-4e51-9d0b-72ea444f8110,dcba2558-9bcc-48a2-b5ba-61b230aa796f

但上述结果导致错误

PG::SyntaxError: ERROR:  syntax error at or near "'(9e24abc1-1422-4e51-9d0b-72ea444f8110,dcba2558-9bcc-48a2-b5ba-61b230aa796f)'"

1 个答案:

答案 0 :(得分:1)

只需将数组作为参数化值传递给查询:

ids = params[:ids].split(',')

@results = MyObject.joins("LEFT OUTER JOIN addresses ON my_objects.address_id = addresses.id")
  .where("my_objects.id IN ? AND EXISTS (SELECT * FROM my_object_times WHERE my_object_times.my_object_id = my_objects.id)", ids)
  .order(order_by)
  .paginate(:page => params[:page])

此外,您应该可以通过执行INNER LEFT join来替换AND EXISTS

@results.left_outer_joins(:addresses)
        .joins(:my_object_times)
        .where(id: ids)

left_outer_joins是Rails 5中的新功能。