构建新对象后,Rails排序关联代理

时间:2015-07-10 11:13:22

标签: ruby-on-rails-4 associations

我有两个型号,

class User < ActiveRecord::Base
  has_many :posts, -> { order('post.id') }
end

class Post < ActiveRecord::Base
  belongs_to: user
end

例如,我有一个@user和两个posts相关联。在做@user.posts时,结果就像。

 [
  [0] #<Post:0x0000000aa53a20> {
                   :id => 3,               
                :title => 'Hello World',
              :comment => 'Long text comes here'
  },
  [1] #<Post:0x0000000aa53a41> {
                   :id => 5,               
                :title => 'Hello World 2',
              :comment => 'Long text comes here too'
  }
] 

现在,我通过@user.posts.build和{建立一个额外的对象 做@user.posts

的结果如下
[
  [0] #<Post:0x0000000aa53a20> {
                   :id => 3,               
                :title => 'Hello World',
              :comment => 'Long text comes here'
  },
  [1] #<Post:0x0000000aa53a41> {
                   :id => 5,               
                :title => 'Hello World 2',
              :comment => 'Long text comes here too'
  },
 [2] #<Post:0x0000000aa53a50> {
                   :id => nil,               
                :title => nil,
              :comment => nil
  },
] 

我真正想要的是,首先按对象排序nil。结果应该看起来像,

[
  [0] #<Post:0x0000000aa53a50> {
                   :id => nil,               
                :title => nil,
              :comment => nil
  },
  [1] #<Post:0x0000000aa53a20> {
                   :id => 3,               
                :title => 'Hello World',
              :comment => 'Long text comes here'
  },
  [2] #<Post:0x0000000aa53a41> {
                   :id => 5,               
                :title => 'Hello World 2',
              :comment => 'Long text comes here too'
  }
] 

也可以通过循环遍历每个对象的自定义方法来完成。但是不想写另一种方法。结果应该在Association Proxy中而不是Array

是否有可能在关联代理本身中实现它?

1 个答案:

答案 0 :(得分:0)

假设您有@posts变量,其中包含nil项。

@posts.sort{|i,j| i.id && j.id ? i <=> j : j.id ? -1 : 1 }

result => [nil, 3, 5]