ruby-on-rails 将SQL转换为Rails查询

avwztpqn  于 2023-04-22  发布在  Ruby
关注(0)|答案(1)|浏览(164)

谁能帮我翻译SQL到Rails Active Record Query?

Station Load (1.5ms)  SELECT "stations".* FROM "stations" WHERE "stations"."id" = $1 LIMIT $2  [["id", "f8cc6584-9794-4863-9e3a-7ac05a1b5d46"], ["LIMIT", 1]]

Connector Load (4.0ms)  SELECT "connectors".* FROM "connectors" WHERE "connectors"."station_id" = $1 AND "connectors"."id" IN ($2, $3)  [["station_id", "f8cc6584-9794-4863-9e3a-7ac05a1b5d46"], ["id", "a476c0a6-bccb-42c7-935f-541031344860"], ["id", "e8e8e80b-6f73-4a66-9345-ae59a042b56d"]]

站有许多连接器。尝试了各种方法,但没有一个是完全一样的SQL以上。谢谢。

j8yoct9x

j8yoct9x1#

如果一个连接器属于一个工作站(如果在连接器模型中设置了该关系),那么您可以尝试使用where进行连接和过滤;

Connector
  .joins(:station)
  .where(
    station_id: "f8cc6584-9794-4863-9e3a-7ac05a1b5d46",
    id: ["a476c0a6-bccb-42c7-935f-541031344860", "e8e8e80b-6f73-4a66-9345-ae59a042b56d"]
  )

同样的,你可以找到这个站,然后得到它的连接器,但是这涉及到两个查询(如果数据库中没有这样的ID的站,它会失败);

Station
  .find("f8cc6584-9794-4863-9e3a-7ac05a1b5d46")
  .connectors
  .where(id: ["a476c0a6-bccb-42c7-935f-541031344860", "e8e8e80b-6f73-4a66-9345-ae59a042b56d"])

相关问题