简体   繁体   English

Rails中的twitter模型关联

[英]twitter model associations in rails

I am trying to build a twitter like data model in rails. 我正在尝试在Rails中构建一个类似数据模型的Twitter。 This is what I have come up with. 这就是我想出的。

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

Should I be using a has_many through association somewhere or is this accurate? 我应该在某个地方通过关联使用has_many还是这样准确?

Edit: The final twitter MVC model. 编辑:最终的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

Edit 2: A concise and accurate explanation 编辑2:简洁准确的解释

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

If two microposts use the same hashtag, you probably don't want to create two database records for that hashtag. 如果两个微博使用相同的主题标签,则您可能不想为该主题标签创建两个数据库记录。 In this case you would use has_many through : 在这种情况下,您可以has_many through以下方式使用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

When you create the Hashtagging migration, make sure it has the micropost_id and hashtag_id columns. 创建Hashtagging迁移时,请确保其具有micropost_idhashtag_id列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM