簡體   English   中英

如何在Rails中一起列出具有不同模型的多態?

[英]How I lists polymorphic with different model together in rails?

在這里我有3種不同的型號
1.Category
2.Branch
3.產品

類別模型有很多分支,而分支有很多不同的產品。

並且每個人都有帶有可評論的多態模型的評論。

這是我的問題。 如何在分支視圖中看到產品評論? 並與分支機構的評論按更新日期排序?

恩。
procuct1已在5/1中更新comment1
branch1在5/2中有comment2
並且product2在5/3中具有comment3

在我的branch1視圖中。 我可以按順序看到以上所有注釋。
注釋1
注釋2
將comment3

使用Subquery和Union將直接有幫助。

假設Branch ID為1,

class Branch < ActiveRecord::Base 
   def all_comments
     Comment.where("commentable_type IN ('Product', 'Branch') 
                   AND commentable_id in (SELECT id FROM products WHERE 
                   branch_id = ? OR ?)", self.id, self.id)
           .order("comments.updated_at ASC")
  end
end

class BranchesController < ApplicationController
  def show
    @branch = Branch.find(params[:id])
    @comments = @branch.all_comments
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM