簡體   English   中英

在Rails中注釋的多態表

[英]Polymorphic Table for comments in Rails

我正在構建一個應用程序,其中多個對象將具有注釋。 我最初設計的應用程序中唯一可以發表評論的是帖子,但是由於更改了方向,使評論變得多態。

這是我的Post模型

class Post < ActiveRecord::Base
  include Bootsy::Container

  belongs_to :user
  belongs_to :post_category
  has_many :comments, as: :commentable

  validates_presence_of :post_category, :user

  scope :sticky, -> { where sticky: true }
  scope :not_sticky, -> { where sticky: false }
  scope :for_category, ->(cat_id) { where post_category_id: cat_id }

  def is_new?
    created_at > Time.now - 24.hours
  end
end

評論模型

class Comment < ActiveRecord::Base
  include Bootsy::Container

  belongs_to :commentable, polymorphic: true
  belongs_to :user
end

目前, Posts (論壇中的帖子)被命名為名稱空間,而對於其他可commentable對象,它們將不被命名空間。 我應該有一個CommentsController在命名空間forum控制器目錄 CommentsController主控制器目錄?

我的路線如下所示(到目前為止):

  # Recently added
  resources :comments,    only: [:create]

  namespace :forum do
    resources :posts,   only: [:index] do
      resources :comments, only: [:create]
    end
    resources :post_categories, only: [:index] do
      resources :posts,   only: [:index, :show, :new, :create, :edit, :update]
    end
  end

如果您希望對每個模型有單獨的意見視圖,那么我認為您應該同時擁有兩個控制器。

暫無
暫無

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

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