2013-03-16 178 views
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 

回答

0

包括触摸:真正的belongs_to的:公司关联。这会在更新值时更新关联公司的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 
+0

非常感谢! – topher 2013-05-28 18:46:01