我确实有以下代码结构:
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
我正在尝试遵循德米特法则,因此资产模型不应该了解 FinancialYear (其中包含年份信息)。我正在尝试使用合并来完成此操作。
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 以这种方式创建查询的原因吗?知道如何更改此结构以使其正常工作吗?任何帮助将不胜感激。