Ruby on rails 4 生成新对象后的Rails排序关联代理
我有两个模型Ruby on rails 4 生成新对象后的Rails排序关联代理,ruby-on-rails-4,associations,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.build和 下面是执行@user.posts [ [0] #<Post:0x0000000aa53a20> {
class User < ActiveRecord::Base
has_many :posts, -> { order('post.id') }
end
class Post < ActiveRecord::Base
belongs_to: user
end
现在,我通过执行@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] # {
:id=>3,
:title=>“你好,世界”,
:comment=>“这里有长文本”
},
[1] # {
:id=>5,
:title=>“Hello World 2”,
:comment=>“这里也有长文本”
},
[2] # {
: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'
}
]
[
[0] # {
:id=>nil,
:title=>nil,
:comment=>nil
},
[1] # {
:id=>3,
:title=>“你好,世界”,
:comment=>“这里有长文本”
},
[2] # {
:id=>5,
:title=>“Hello World 2”,
:comment=>“这里也有长文本”
}
]
也可以通过自定义方法通过循环遍历每个对象进行排序。但我不想写另一个方法。结果应该是关联代理,而不是数组
有可能在关联代理本身中实现它吗 假设您有
@posts
变量,其中包含nil
项
@posts.sort{|i,j| i.id && j.id ? i <=> j : j.id ? -1 : 1 }
result => [nil, 3, 5]
@posts.sort{i,j | i.id&&j.id?i j:j.id?-1:1}
结果=>[nil,3,5]
@posts.sort{|i,j| i.id && j.id ? i <=> j : j.id ? -1 : 1 }
result => [nil, 3, 5]