简体   繁体   中英

multiple belongs_to models in Rails

I have a comments model that is currently working with Articles. I would now like to have users be able to comment on the Coffeeshop reviews. Am I able to use the same comment table, or should I have a separate one (feels janky). I've not long been building with RoR (a few weeks) so still trying to get the hang of the basics.

Would I nest them in routes.rb (and how)

  resources :coffeeshops do
  resources :articles do
    resources :comments
  end

or

  resources :coffeeshops do
    resources :comments
  end

  resources :articles do
    resources :comments
  end

My models look like:

User

class User < ApplicationRecord
has_many :comments
end

Comments

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :article
  belongs_to :coffeeshop
end

Articles

class Article < ApplicationRecord
  has_many :comments, dependent: :destroy
end

Coffeeshops

class Coffeeshop < ApplicationRecord
has_many :comments, dependent: :destroy

I'm then assuming I need a foreign key to tie the user and comments together, and then also the comments to the article/coffeeshop.

I'd use a polymorphic association.

http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

class User < ApplicationRecord
  has_many :comments
end

class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :commentable, polymorphic: true
end

class Article < ApplicationRecord
  has_many :comments, as: :commentable
end

class Coffeeshop < ApplicationRecord
  has_many :comments, as: :commentable
end

For some more information about setting up the routes/controller:

https://rubyplus.com/articles/3901-Polymorphic-Association-in-Rails-5 http://karimbutt.github.io/blog/2015/01/03/step-by-step-guide-to-polymorphic-associations-in-rails/

You can use comment model for both comments for articles and coffeeshops, but (because by default rails uses ids as primary and foreign keys I assume you use ids too) you will have to add column to comments table, where you set the comment type (You can create Enumerator in comment model, where you set 2 possible value types, each for article and coffeeshop models). If you don't add the column it will result in weird, hard to track bug where you can see comments for article on coffeeshop with same id and vise-versa.

UPD: he's little guide on using enums for rails models: http://www.justinweiss.com/articles/creating-easy-readable-attributes-with-activerecord-enums/ you will have to use it not in actual add comment form, but behind the scenes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM