Ruby on rails 在用户特定的贴子标记上有许多关联
我对Rails还相当陌生,多对多的关系让我有些不知所措。在我的应用程序中,一个Ruby on rails 在用户特定的贴子标记上有许多关联,ruby-on-rails,ruby,has-many-through,polymorphic-associations,tagging,Ruby On Rails,Ruby,Has Many Through,Polymorphic Associations,Tagging,我对Rails还相当陌生,多对多的关系让我有些不知所措。在我的应用程序中,一个用户有很多帖子,可以看到其他人的帖子。他们可以通过添加一个标签来为自己的帖子分类,每个帖子只有一个标签。其他用户可以用不同的标签来标记同一篇文章,这只会为他们显示 如何在Rails中建立这种关系 class User < ActiveRecord::Base has_many :tags class Post < ActiveRecord::Base has_one :tag, :throug
用户
有很多帖子,可以看到其他人的帖子
。他们可以通过添加一个标签来为自己的帖子分类,每个帖子只有一个标签。其他用户可以用不同的标签来标记同一篇文章,这只会为他们显示
如何在Rails中建立这种关系
class User < ActiveRecord::Base
has_many :tags
class Post < ActiveRecord::Base
has_one :tag, :through => :user # correct?
class Tag < ActiveRecord::Base
belongs_to :user
has_many :posts
class用户:用户#正确吗?
类标记
如果我理解正确,我认为您希望这样:
class User < ActiveRecord::Base
has_many :tags
class Post < ActiveRecord::Base
has_many :tags, :through => :user
class Tag < ActiveRecord::Base
belongs_to :user
has_many :posts
你可以这样写
class User < ActiveRecord::Base
has_many :tags
has_many :posts, through: :tags
class Post < ActiveRecord::Base
has_many :tags
class Tag < ActiveRecord::Base
belongs_to :user
belongs_to :post
class用户
所以每个帖子都有很多标签,但每个用户只有一个。顺便说一句,您可以再添加1个模型来分别存储标记和用户标记
class User < ActiveRecord::Base
has_many :user_tags
has_many :tags, through: :user_tags
has_many :posts, through: :user_tags
class Post < ActiveRecord::Base
has_many :user_tags
class Tag < ActiveRecord::Base
has_many :user_tags
class UserTags < ActiveRecord::Base
belongs_to :user
belongs_to :tag
belongs_to :post
class用户
用户标签模型的优点是什么?保持标签的唯一性。例如,如果user1和user2通过标记“ruby”来标记post1,那么在第一种情况下,它将是两个标记“ruby”,具有不同的用户。在第二种情况下,您可能有1个标记“ruby”
class User < ActiveRecord::Base
has_many :user_tags
has_many :tags, through: :user_tags
has_many :posts, through: :user_tags
class Post < ActiveRecord::Base
has_many :user_tags
class Tag < ActiveRecord::Base
has_many :user_tags
class UserTags < ActiveRecord::Base
belongs_to :user
belongs_to :tag
belongs_to :post