Matthias
Matthias

Reputation: 4375

active record all query from instance

Maybe somebody has an idea how I could solve following problem:

I have a Model and want to query it.

def MyModel < ActiveRecord::Base

  # instance method
  def all
    my_models = MyModel.all
    my_models.?? # order my_models ActiveRecord::Relation, that the instance which calls the .all instance method is at first position, and the rest is sorted somehow,..whatever.
  end

end

How could I solve that?

EDIT:

Example: MyModel has a name. I have four instances of MyModel

MyModel.all => #<ActiveRecord::Relation [#<MyModel id: 1, name: "name1">, #<MyModel id: 2, name: "name2">, #<MyModel id: 3, name: "name3">, #<MyModel id: 4, name: "name4">]>

And I want now:

MyModel.find(1).all => #<ActiveRecord::Relation [#<MyModel id: 1, name: "name1">, #<MyModel id: 2, name: "name2">, #<MyModel id: 3, name: "name3">, #<MyModel id: 4, name: "name4">]>

MyModel.find(2).all => #<ActiveRecord::Relation [#<MyModel id: 2, name: "name2">, #<MyModel id: 1, name: "name1">, #<MyModel id: 3, name: "name3">, #<MyModel id: 4, name: "name4">]>

MyModel.find(3).all => #<ActiveRecord::Relation [#<MyModel id: 3, name: "name3">, #<MyModel id: 1, name: "name1">, #<MyModel id: 2, name: "name2">, #<MyModel id: 4, name: "name4">]>

Upvotes: 2

Views: 291

Answers (2)

boulder
boulder

Reputation: 3266

A possible solution would be taking advantage of the fact that an ActiveRecord::Relation instance responds to many of the Array instance methods:

def all
  ary = self.class.order(:id)
  ary = ary.unshift(self)
  ary.uniq
end

However this returns an instance of Array so you can't keep appending additional scopes. Up to you to decide whether that's acceptable in your case.

Upvotes: 1

deefour
deefour

Reputation: 35370

I believe this accomplishes what you're asking.

def all
  self.class.order("case when id = #{id} then 0 else id end")
end

Upvotes: 2

Related Questions