有没有办法避免这个查询,所以我可以在Rails 5.0.0.1?

时间:2017-02-02 03:09:50

标签: ruby-on-rails postgresql

我在带有Postgres 9.5.5的Heroku上的Rails 5.0.0.1应用程序中设置了以下模型:

class Tape < ApplicationRecord
  has_many :numbers
  belongs_to :player
end

class Player < ApplicationRecord
  has_many :tapes
  has_many :snapshots
end

class Number < ApplicationRecord
  belongs_to :tape
  belongs_to :snapshot
end

class Snapshot < ApplicationRecord
  has_many :numbers, dependent: :destroy
  belongs_to :player
end

#I want to order @numbers by the created_at field of its other parent, Snapshot, not tape
@tape = Tape.includes(player: {snapshots: :numbers}).find 55
@numbers = Number.includes(snapshot: :player).where(players: {id: @tape.player_id}, tape_id: @tape.id).order('snapshots.created_at DESC')

似乎我不得不做额外的SQL工作,只是为了通过其父快照订购@numbers。

我尝试了@tape.numbers.joins(:snapshot).order('snapshots.created_at DESC'),我看到一个SQL查询以&#39; .... ORDER BY&#34;数字&#34;。&#34; id&#34; ASC,snapshots.created_at DESC&#39;这意味着Rails将此解释为我想要按numbers.id排序 - 我不会这样做。我只想通过snapshots.created_at订购。现在,像@tape.numbers.joins...这样的查询也将是一个额外的SQL查询。 2个问题:

1)我能写的代码是什么导致SQL工作量最少?或者是我几乎拥有的东西?

2)为什么rails会在'....ORDER BY "numbers"."id"中插入额外的@tape.numbers.joins(:snapshot).order('snapshots.created_at DESC')子句?

0 个答案:

没有答案