0

このような会社のモデルがあります

class Company < ActiveRecord::Base
  has_many :values
end

次に、値モデルは次のようになります

class Value < ActiveRecord::Base
  belongs_to :company
  default_scope order: 'created_at ASC'
end

会社が最新の値に基づいて並べ替えられるように、会社の既定の並べ替え順序を作成したいと考えています。最新の値を持つ会社が最初になります。このようなもの:

default_scope order: 'companies.values.last.created_at DESC'

しかし、それを会社のモデルに入れると、次のエラーが発生します。

SQLite3::SQLException: near "values": syntax error: SELECT  "companies".* FROM "companies"  WHERE "companies"."id" = ? ORDER BY companies.values.last.calculated_at DESC LIMIT 1
4

1 に答える 1

0

belongs_to :company 関連付けに touch: true を含めます。これにより、値が追加されるたびに、関連する会社の updated_at 列が更新されます。これで、updated_at 列で並べ替えることができます。

class Value < ActiveRecord::Base
  belongs_to :company, touch: true
end

class Company < ActiveRecord::Base
 has_many :values
 default_scope order: 'updated_at DESC'
end
于 2013-04-27T20:08:09.943 に答える