Rails中的注释的多态表

时间:2016-07-14 13:52:17

标签: ruby-on-rails polymorphism

我正在构建一个应用程序,其中多个对象将有注释。我最初设计的应用程序中唯一可以发表评论的是Posts,但是因为已经改变了方向以使评论变得多变。

这是我的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控制器目录 a 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

1 个答案:

答案 0 :(得分:0)

如果你想为每个模型提供单独的评论视图,那么在我看来你应该有两个控制器。