活动记录来自实例的所有查询

时间:2013-08-06 16:54:12

标签: ruby-on-rails activerecord

也许有人知道如何解决以下问题:

我有一个模型,想要查询它。

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

我怎么能解决这个问题?

修改

实施例: MyModel有一个名字。 我有四个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">]>

我现在想要:

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">]>

2 个答案:

答案 0 :(得分:2)

我相信这可以完成你所要求的。

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

答案 1 :(得分:1)

可能的解决方案是利用ActiveRecord :: Relation实例响应许多Array实例方法这一事实:

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

但是,这会返回一个Array实例,因此您无法继续追加其他范围。由你来决定你的情况是否可以接受。