按另一个相关模型属性排序 - Ruby 在 Rails

Sorting by another related model attributes - Ruby on Rails

我有两个相互关联的模型,如下所示

class Weed < ApplicationRecord
  has_many :user_transactions, :dependent => :destroy
end

这个 weed 模型有一个属性名称 county

及相关型号:

class UserTransaction < ApplicationRecord
  belongs_to :weed
end

现在我想在 weed 模型中按 county 排序的基础上从 UserTransaction 模型中获取记录,并按县查找。

请给我建议,我怎样才能以最小的复杂度得到正确的结果。

谢谢。

UserTransaction.joins(:weed).order('weeds.county DESC')
UserTransaction.joins(:weed).where(weeds: { county: 'something' }).order('weeds.county DESC')

如果你想按排序,你可以这样做:

UserTransaction.joins(:weed).order("weeds.county DESC")

或者如果您想按 county 查找,请使用 :

UserTransaction.joins(:weed).where("weeds.county"=> "xyz")