thedanotto
thedanotto

Reputation: 7307

ActiveRecord sort_by model's association

I want to use a where clause to retrieve all the correct ItemAttributes, then sort by the column order in Static.

Relationships:

class ItemAttribute < ActiveRecord::Base
  belongs_to :static, primary_key:"name", foreign_key:"name"
end

class Static < ActiveRecord::Base
  has_many :item_attributes, :foreign_key => 'name', :primary_key => 'name'
end

Code that doesn't quite do it...

      @items = ItemAttribute.where(level:5)
      @sorted = @items.sort_by(&:static.order)

Upvotes: 0

Views: 143

Answers (2)

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42789

I like using scopes and keeping specifics of each class in it's class, for something like this I could add a scope to Static model,

class Static < ActiveRecord::Base
  scope :sort_by_order, -> { order(order: :desc) } # or asc if you want
end

Then use that scope in the query

@sorted_items = ItemAttribute.joins(:static).where(level: 5).merge(Static.sort_by_order)

Upvotes: 2

user3118220
user3118220

Reputation: 1468

@sorted_items = ItemAttribute.include(:static).where(level:5).order('statics.order')

Upvotes: 0

Related Questions