Search code examples
ruby-on-railsrubyhas-many-throughpolymorphic-associationstagging

Has many association on user-specific post tagging


I’m fairly new to Rails, and many-to-many relationships is a bit over my head. In my app, a User has many and can see others' Posts. They can categorise the posts for themselves by adding a Tag— just one per post. Other users can tag the same post with a different tag and that shows up just for them.

How can I make this relationship in 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

Solution

  • You can write it in this way

    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
    

    So each Post will have many Tags, but only 1 for each User. Btw, you can add 1 more model to store Tags and Users tagging separately

    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