2014-11-02 66 views
0

這裏是新手導軌。我正在製作一個應用來管理用戶,文本片段,片段評論以及喜歡的內容。在導軌模型中選擇兩個可能的關聯之一

每個用戶都有很多片段,並且有很多評論。 每個片段都屬於某個用戶,有很多評論,並且可以有很多喜歡的片段。 每個評論屬於某個用戶,屬於一個片段,並可以有很多喜歡。

我的問題是與Like模型。一個like將屬於某個用戶,並且屬於一個片段或一個評論。

我的遷移是這樣的:

class CreateLikes < ActiveRecord::Migration 
    def change 
    create_table :likes do |t| 
     t.references :user 
     t.references :snippet # or :comment...? 

     t.timestamps 
    end 
    end 
end 

我的片段模式:

class Snippet < ActiveRecord::Base 
    has_many :comments 
    has_many :likes 
    belongs_to :user 
end 

我的評論模式:

class Comment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :snippet 
    has_many :likes 
end 

我喜歡模型:

class Like < ActiveRecord::Base 
    belongs_to: :user 
    # belongs to either :snippet or :comment, depending on 
    # where the like is, and what controller it was submitted to 
end 

我不能同時引用這兩個,我覺得爲應用中的每種內容創建一種新類型的Like會很麻煩。

如何決定是在引用片段還是引用每個類似的評論之間進行選擇?

回答

5

你在找什麼叫做Polymorphic Association,並且很容易用Rails和活動記錄完成。

您需要稍微修改Like遷移以包含額外的_type列。最簡單的方法就是遷移。

def change 
    create_table :likes do |t| 
    # other columns ... 
    t.references :likeable, polymorphic: true 
    t.timestamps 
    end 
end 

這一切確實是創建一個likeable_idlikeable_type列,將引用特定id和類type(在你的情況下,type值可以是「評論」或「片段」)。在此之後,您可以設置您的關聯像這樣

class Like < ActiveRecord::Base 
    belongs_to :likeable, polymorphic: true 
end 

class Snippet < ActiveRecord::Base 
    has_many :likes, as: :likeable 
end 

class Comment < ActiveRecord::Base 
    has_many :likes, as: :likeable 
end 
1

您需要看看Rails中的Polymorphic Associations。 RailsCast在這個例如http://railscasts.com/episodes/154-polymorphic-association上有一個很好的插曲。

在這裏,我將創造多態模型,並評論片段可愛

class CreateLikes < ActiveRecord::Migration 
    def change 
    create_table :likes do |t| 
     t.integer :likeable_id 
     t.string :likeable_type 
     t.references :user 
     t.timestamps 
    end 
    end 
end 
class Snippet < ActiveRecord::Base 
    has_many :comments 
    has_many :likes, as: :likeable 
    belongs_to :user 
end 
class Comment < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :snippet 
    has_many :likes, as: :likeable 
end 

class Like < ActiveRecord::Base 
    belongs_to: :user 
    belongs_to :likeable, :polymorphic => true 
    # belongs to either :snippet or :comment, depending on 
    # where the like is, and what controller it was submitted to 
end