Search code examples
ruby-on-railsrubyactiverecordpolymorphic-associations

Impossible Rails Syntax: Order has_many with polymorphic association


Statically-typed, compile-time-checked programmer brain, here, struggling with a rails function call.

In a model when we specify has_many, we can specify the sort order like this has_many :requirements, -> { order(created_at: :asc) }, :dependent => :destroy.

But when we have a polymorphic association such as this has_many :text_fields, as: :describable, :dependent => :destroy how can we add the sorting lambda?

I have tried every possible permutation of syntax except, apparently, the correct one.


Solution

  • You have clarified that it is the child records (text_fields) that you want ordered. You could use a default_scope, like so:

    class ParentModel < ApplicationRecord
      has_many :text_fields, as: :describable, :dependent => :destroy
    end
    
    class TextField < ApplicationRecord
      default_scope { order(created_at: :asc) }
    end
    

    But think hard before doing so because default_scope is evil. Among other things, you can't override an order that is defined in a default_scope. I am not familiar with requirements, but you may not be able to override the order defined within requirements either.

    I think you are much better served creating a scope like so:

    class ParentModel < ApplicationRecord
      has_many :text_fields, as: :describable, :dependent => :destroy
    end
    
    class TextField < ApplicationRecord
      scope :default_order, -> { order(created_at: :asc) }
    end
    

    Then call it explicitly when you want your records ordered that way:

    TextField.all.default_order
    

    or

    parent_record.text_fields.default_order