How to use union correctly in Rails 4?

I have the 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 would like to be able to call the Asset model like this:

Asset.order_by_year

      

I am trying to follow the Law of Demeter and therefore the Asset Model does not need to know about FinancialYear (which contains year information). I am trying to use merge for 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 an error message because lines 3 and 4 are in the wrong order. Any idea why Rails is creating a request this way? Any idea how to change this structure to make it work? Any help would be greatly appreciated.

+3


source to share





All Articles