我确实有以下代码结构:
class Asset < ActiveRecord::Base
belongs_to :state
scope :order_by_year, -> { joins(:state).merge(State.order_by_year) }
...
class State < ActiveRecord::Base
belongs_to :financial_statement
has_many :assets
scope :order_by_year, -> { joins(:financial_statement).merge(FinancialStatement.order_by_year) }
...
class FinancialStatement < ActiveRecord::Base
belongs_to :financial_year
has_many :states
scope :order_by_year, -> { joins(:financial_year).merge(FinancialYear.order_by_year) }
...
class FinancialYear < ActiveRecord::Base
has_many :financial_statements
scope :order_by_year, -> { order("financial_years.year DESC") }
...
我希望能够像这样调用资产模型:
Asset.order_by_year
我正在尝试遵循Demeter法,因此资产模型不应该知道FinancialYear(其中包含年份信息)。我正在尝试使用merge来实现这一目标。
Asset.order_by_year creates the following sql:
1: SELECT `assets`.* FROM `assets`
2: INNER JOIN `states` ON `states`.`id` = `assets`.`state_id`
3: LEFT OUTER JOIN `financial_years` ON `financial_years`.`id` = `financial_statements`.`financial_year_id`
4: LEFT OUTER JOIN `financial_statements` ON `financial_statements`.`id` = `states`.`financial_statement_id`
5: ORDER BY financial_years.year DESC
这会出现错误消息,因为第3行和第4行的顺序错误。知道为什么Rails会以这种方式创建查询吗?知道如何更改此结构以使其工作吗?任何帮助将不胜感激。