我有两个模型帖子和主题,它们具有一对多的关系
#Post.rb
class Post < ApplicationRecord
belongs_to :topic
validates :topic_id, presence: true
validates :title, presence: true
validates :body, presence: true
end
如果我通过调用Post.all
来获得一系列帖子,例如
#<ActiveRecord::Relation [#<Post id: 1, title: "Rails Code", body: "class TopicsController < ApplicationController\r\n ...", created_at: "2018-05-22 09:34:15", updated_at: "2018-05-22 09:34:15", topic_id: "2">,
#<Post id: 2, title: "Post with tags", body: "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq...", created_at: "2018-05-22 11:48:54", updated_at: "2018-05-22 11:48:54", topic_id: "2">,
#<Post id: 3, title: "12hello world12", body: "12312sdfsdfsdsdsdsd31231231231231", created_at: "2018-05-23 12:54:02", updated_at: "2018-05-23 12:54:02", topic_id: "2">,
#<Post id: 4, title: "12hello world12", body: "12312sdfsdfsdsdsdsd31231231231231", created_at: "2018-05-23 12:54:09", updated_at: "2018-05-23 12:54:09", topic_id: "1">,
#<Post id: 5, title: "12hellsdssdo world12", body: "12312sdfsdfsdsdsdsd31231231231231", created_at: "2018-05-23 12:54:15", updated_at: "2018-05-23 12:54:15", topic_id: "1">]>
有没有办法可以按照topic_id
对它们进行分组,这样我就可以按主题显示它们
示例
Topic - 1
post 1 post2 post 3
Topic -2
post4 post5
答案 0 :(得分:2)
找到答案。
你可以使用ruby的Enumerable#group_by
:
post.group_by{|post| post.topic_id}
答案 1 :(得分:2)
使用此:
Post.all.group_by(&:topic_id).each do |topic_id, posts|
...
end