Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在用户特定的贴子标记上有许多关联_Ruby On Rails_Ruby_Has Many Through_Polymorphic Associations_Tagging - Fatal编程技术网

Ruby on 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还相当陌生,多对多的关系让我有些不知所措。在我的应用程序中,一个
用户
有很多帖子,可以看到其他人的
帖子
。他们可以通过添加一个
标签来为自己的帖子分类,每个帖子只有一个标签。其他用户可以用不同的标签来标记同一篇文章,这只会为他们显示

如何在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