Multi-Parent Ruby on rails Model

In my Rails application, I have two models: articles and projects that are user related. I want to add comments to each of these models. What is the best way to structure this?

Here is my current setup:

class Comment < ActiveRecord::Base
  belongs_to :article
  belongs_to :project
end

class Article < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Project < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class User < ActiveRecord::Base
  has_many :articles
  has_many :projects
  has_many :comments, :through => :articles
  has_many :comments, :through => :projects
end 

Is this the right way to handle structure? If so, how do I manage the CommentController comment to have article_id if it was created through the article, and project_id if it was created through Project? Are there any special routes that I have to configure?

One final comment: comments do not always have to have a user. Since this is, if for my site, I want anonymous viewers to be able to post comments. Is this a trivial task?

+3
3

Comment . .

Rails Railscast screencast-men Ryan Bates.

+5

ArticleComment ProjectComment , , , .

0

Source: https://habr.com/ru/post/1714132/


All Articles