2013-01-01 117 views
2

我想在rails中構建像數據模型一樣的twitter。這是我想出的。在軌道中的twitter模型協會

class User < ActiveRecord::Base 
    has_many :microposts, :dependent => :destroy 
end 

class Micropost < ActiveRecord::Base 
    belongs_to :user 
    has_many :mentions 
    has_many :hashtags 
end 

class Mention< ActiveRecord::Base 
    belongs_to :micropost 
end 

class Hashtag < ActiveRecord::Base 
    belongs_to :micropost 
end 

我應該在某處使用has_many關聯還是這樣準確?

編輯:最終的twitter MVC模型。

class User < ActiveRecord::Base 
    has_many :microposts, :dependent => :destroy 

    userID 
end 

class Micropost < ActiveRecord::Base 
    belongs_to :user 

    has_many :link2mentions, :dependent => :destroy 
    has_many :mentions, through: :link2mentions 

    has_many :link2hashtags, :dependent => :destroy 
    has_many :hashtags, through: :link2hashtags 

    UserID 
    micropostID 
    content 
end 

class Link2mention < ActiveRecord::Base 
    belongs_to :micropost 
    belongs_to :mention 

    linkID 
    micropostID 
    mentionID 
end 

class Mention < ActiveRecord::Base 
    has_many :link2mentions, :dependent => :destroy 
    has_many :microposts, through: :link2mentions 

    mentionID 
    userID 
end 

編輯2:簡潔而準確的解釋

http://railscasts.com/episodes/382-tagging?view=asciicast

回答

1

如果兩個微柱使用相同的主題標籤,你可能不希望創建爲主題標籤兩臺數據庫記錄。在這種情況下,你可以使用has_many through

class Hashtagging < ActiveRecord::Base 
    belongs_to :micropost 
    belongs_to :hashtag 
end 

class Hashtag < ActiveRecord::Base 
    has_many :hashtaggings 
    has_many :microposts, through: :hashtaggings 
end 

class Micropost < ActiveRecord::Base 
    ... 
    has_many :hashtaggings 
    has_many :hashtags, through: :hashtaggings 
end 

當您創建Hashtagging遷移,確保它有micropost_idhashtag_id列。

+0

我不確定我關注。兩個微博也可以有同樣的提及。我需要在這裏使用has_many模型嗎? –

+1

是的,對於提及 – mihai

+0

也一樣。哈希標籤表的用途是什麼。如果要存儲鏈接到hashtags表,爲什麼每個micropost都有多個hashtaggings? –