2017-04-11 79 views
0

我有一个当前正在使用Articles的注释模型。我现在想让用户能够评论Coffeeshop评论。我能否使用相同的评论表,或者我应该有一个单独的评论表(感觉很好)。我一直没有用RoR(几个星期)来构建,所以仍然试图掌握基础知识。Rails中的多个belongs_to模型

我会窝他们routes.rb中(以及如何)

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

resources :coffeeshops do 
    resources :comments 
    end 

    resources :articles do 
    resources :comments 
    end 

我的模式是这样的:

用户

class User < ApplicationRecord 
has_many :comments 
end 

评论

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

文章

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

咖啡店

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

我再假设我需要一个外键,以配合用户和评论在一起,然后还有评论文章/咖啡店。

回答

6

我会使用多态关联。

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 

有关设置路由/控制器的一些详细信息:

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/

+0

好的。用户仍然只有'has_many:comments'? –

+1

@SimonCooper:是的。当然是用':as::commentable'。 –

+0

就像塞尔吉奥已经提到的一样;是。我编辑了包含用户模型的答案。 – Laurens

0

你可以使用评论模型来评论文章和咖啡休息室,但是(因为默认情况下,rails使用ID作为主键和外键,我假设你也使用ID),你将不得不添加列到评论表,你设置了评论类型(您可以在评论模型中创建Enumerator,您可以在其中为文章和咖啡店模型设置2种可能的值类型)。如果你不添加列,它会导致奇怪的,很难追踪错误,你可以在同一个id上看到coffeeshop上的文章的评论,反之亦然。

UPD:他是关于使用枚举为rails模型的小指南:http://www.justinweiss.com/articles/creating-easy-readable-attributes-with-activerecord-enums/您将不得不使用它实际添加评论表单,但在幕后。

+0

确定这是有道理的。目前我的评论表为'article_id'列。我会为'coffeeshop_id'添加一个新列吗?或者有一个说评论类型的列,值是文章或咖啡店之一? –

+0

你可能想在这种情况下使用多态关联。在你的表中,你基本上有commented_resource_id作为整数,并且type(在模型中由枚举处理,但在表中也是整数)。然后你想在belongs_to关系中设置'polymorphic:true'。其实,这是另一个帮助我弄清楚的指南:https:// launchschool。com/blog/understanding-polymorphic-associations-in-rails –