Rails sort association proxy after new object is build -


i have 2 models,

class user < activerecord::base   has_many :posts, -> { order('post.id') } end  class post < activerecord::base   belongs_to: user end 

for instance i'm having @user , 2 posts associated. while doing @user.posts, result like.

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

now, i'm building 1 more object doing @user.posts.build , below result of doing @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   }, ]  

what want is, sort object nil first. result should like,

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

it can done custom method sort looping through each object. don't want write method. result should in association proxy , not array

is possible achieve in association proxy itself?

suppose, have @posts variable contains nil item.

@posts.sort{|i,j| i.id && j.id ? <=> j : j.id ? -1 : 1 }  result => [nil, 3, 5] 

Comments