2017-04-11 84 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 –