I do have a following code structure:
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") }
...
I'd like to be able to call Asset model like this:
Asset.order_by_year
I'm trying to follow Law of Demeter and therefore Asset model should not know about FinancialYear (which holds the year information). I'm trying to use merge to accomplish this.
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
This gives error message because rows 3 and 4 are in wrong order. Any idea why Rails creates the query this way? Any idea how to change this structure in order to get it work? Any help would be greatly appreciated.