【问题标题】:twitter model associations in railsRails 中的 Twitter 模型关联
【发布时间】:2012-12-16 01:56:51
【问题描述】:

我正在尝试在 Rails 中构建类似 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

【问题讨论】:

    标签: ruby-on-rails database-design twitter model


    【解决方案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 列。

    【讨论】:

    • 我不确定我是否遵循。两个微博也可以有相同的提及。我必须在这里使用 has_many through 模型吗?
    • 标签表的用途是什么。如果是存储标签表的链接,为什么每个微博都有多个标签?
    • hashtaggings 是join model。它拥有其他两个模型之间的关联。在数据库中,您可能有一些 id 为 1,2 的微博和一些 id 为 1,2,3,4 的主题标签,然后这些标签将类似于 (micropost_id: 1, hastag_id: 3)(micropost_id: 2, hastag_id: 4) 等等。
    • 我相信这与您所解释的解决方案类似。链接表是标签表。谢谢! 2.bp.blogspot.com/_qQDfjePruAM/SwMtLR97BzI/AAAAAAAAElo/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多