2015-07-10 23 views
1

我有兩個型號,Rails的排序協會代理是建立

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 
    }, 
] 

什麼其實我想要的是,對以下結果由物體與零第一排序。結果應該看起來像,

[ 
    [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' 
    } 
] 

它也可以通過自定義方法通過循環每個對象進行排序。但不想寫另一種方法。結果應該在關聯代理而不是陣列

它有可能在關聯代理本身實現它嗎?

回答

0

假設您有@posts變量,它包含nil項目。

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

result => [nil, 3, 5]