[英]How to aggregate model instances into one variable in Rails?
在項目控制器內部,我有這個:
def index
@projects = Project.all
@projects.each do |pr|
@posts = @posts.what_do_i_use_here(pr.posts.all)
end
@posts.order('created_at DESC')
end
每個項目都有其帖子,現在我要將所有項目的帖子匯總到一個變量中,該怎么做? 注意,這可以毫無問題地從上一個項目中獲取帖子:
@projects.each do |pr|
@posts = pr.posts.all
end
如果您僅對與項目相關的帖子感興趣:
帖子僅與項目相關
@posts = Post.order(created_at: :desc)
與多態相關的帖子
@posts = Post.where(posted_type: 'Project').order(created_at: :desc)
其中posted_type
是多態關系的類型字段
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.