ruby-on-rails 为什么order()不对papertrail版本关联生效?

oprakyz7  于 2023-10-21  发布在  Ruby
关注(0)|答案(1)|浏览(93)

我正在使用papertrail gem来跟踪我的问题和结果模型的版本。
我可以成功订购Papertrail::这样的版本:

PaperTrail::Version.order(created_at: :desc).limit(1).select(:id)
  PaperTrail::Version Load (0.3ms)  SELECT "versions"."id" FROM "versions" ORDER BY "versions"."created_at" DESC LIMIT $1  [["LIMIT", 1]]
=> [#<PaperTrail::Version:0x00007f4d90820f20 id: 32>]

PaperTrail::Version.order(created_at: :asc).limit(1).select(:id)
  PaperTrail::Version Load (0.9ms)  SELECT "versions"."id" FROM "versions" ORDER BY "versions"."created_at" ASC LIMIT $1  [["LIMIT", 1]]
=> [#<PaperTrail::Version:0x00007f4d90935500 id: 10>]

但是当我通过关联尝试同样的事情时,order()似乎不起作用!
为了说明,这里有一个结果对象,它有9个相关的版本:

Outcome.last.versions.count
  Outcome Load (0.4ms)  SELECT "outcomes".* FROM "outcomes" ORDER BY "outcomes"."id" DESC LIMIT $1  [["LIMIT", 1]]
  PaperTrail::Version Count (0.4ms)  SELECT COUNT(*) FROM "versions" WHERE "versions"."item_id" = $1 AND "versions"."item_type" = $2  [["item_id", 1], ["item_type", "Outcome"]]
=> 9

created_at排序应该返回不同的版本记录,但它们没有。:/

Outcome.last.versions.order(created_at: :asc).limit(1).select(:id)
  Outcome Load (0.5ms)  SELECT "outcomes".* FROM "outcomes" ORDER BY "outcomes"."id" DESC LIMIT $1  [["LIMIT", 1]]
  PaperTrail::Version Load (0.5ms)  SELECT "versions"."id" FROM "versions" WHERE "versions"."item_id" = $1 AND "versions"."item_type" = $2 ORDER BY "versions"."created_at" ASC, "versions"."id" ASC LIMIT $3  [["item_id", 1], ["item_type", "Outcome"], ["LIMIT", 1]]
=> [#<PaperTrail::Version:0x00007f4d83e6f140 id: 29>]

Outcome.last.versions.order(created_at: :desc).limit(1).select(:id)
  Outcome Load (0.4ms)  SELECT "outcomes".* FROM "outcomes" ORDER BY "outcomes"."id" DESC LIMIT $1  [["LIMIT", 1]]
  PaperTrail::Version Load (0.4ms)  SELECT "versions"."id" FROM "versions" WHERE "versions"."item_id" = $1 AND "versions"."item_type" = $2 ORDER BY "versions"."created_at" ASC, "versions"."id" ASC, "versions"."created_at" DESC LIMIT $3  [["item_id", 1], ["item_type", "Outcome"], ["LIMIT", 1]]
=> [#<PaperTrail::Version:0x00007f4d83e66e00 id: 29>]
cetgtptt

cetgtptt1#

好吧-当我写这篇文章的时候,我意识到可能有一个默认的范围。果然有答案是在查询关联时使用.unscoped,例如

Outcome.last.versions.unscoped.order(created_at: :desc).limit(1).select(:id)

相关问题