我有两个型号,
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
是否有可能在关联代理本身中实现它?
答案 0 :(得分:0)
假设您有@posts
变量,其中包含nil
项。
@posts.sort{|i,j| i.id && j.id ? i <=> j : j.id ? -1 : 1 }
result => [nil, 3, 5]