mr_muscle
mr_muscle

Reputation: 2900

Rails sort association with scope mixed ordering

In CashTransaction model I've got default scope:

class CashTransaction < ApplicationRecord
   belongs_to :cashbook

   default_scope { order(id_number: :desc) }
end

In one of service I use association to pull cash_transactions:

  def parsed_cash_transactions
    cashbook.cash_transactions.map do |cash_transaction|
      {
        position: cash_transaction.id_number,
        # ...
        # other data
      }
    end
  end

I use this method in other place of code to create prawn table and many other related things:

  def transaction_items
    @last_position = parsed_cash_transactions.last[:position]

    parsed_cash_transactions.each do |cash_transaction|
    # ...
    # some other actions
  end

The thing is default scope doesn't worked here - most are correct but transaction_items method returns me randomly mixed data (e.g. I've got position 2 at 10, 11 around 200 and so on...). How to have these transaction_items data sorted by id_number ?

Upvotes: 0

Views: 63

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14900

default_scope is probably one of the worst part of Rails and should be avoided at all costs.*

You can just create a custom scope if you have some special ordering you do often.

scope :ordered, -> { order(id_number: :desc) }

#
cashbook.cash_transactions.ordered

* Of course that is a bit of a hyperbole but the truth stands that default_scope is something you have to very wary of, because the way it works with associations and other stuff is very counter-intuitive.

https://riptutorial.com/ruby-on-rails/example/17746/beware-of--default-scope

https://www.reddit.com/r/rails/comments/ha6gqj/default_scope_is_evil/

Upvotes: 2

Related Questions