2

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

我有一个模型并想查询它。

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

2 回答 2

2

我相信这可以满足您的要求。

def all
  self.class.order("case when id = #{id} then 0 else id end")
end
于 2013-08-06T17:23:57.207 回答
1

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

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

但是,这会返回一个 Array 实例,因此您不能继续附加其他范围。由您决定在您的情况下是否可以接受。

于 2013-08-06T17:40:43.320 回答