2

我正在尝试在 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

4

1 回答 1

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列。

于 2013-01-01T10:49:25.253 回答