How do you model “Likes” in rails?

前端 未结 4 1605
太阳男子
太阳男子 2021-02-01 09:36

I have 3 models: User, Object, Likes

Currently, I have the model: a user has many Objects. How do I go about modeling:

1) A user can like many objects

2

4条回答
  •  难免孤独
    2021-02-01 10:21

    To elaborate further on my comment to Brandon Tilley's answer, I would suggest the following:

    class User < ActiveRecord::Base
      # your original association
      has_many :things
    
      # the like associations
      has_many :likes
      has_many :liked_things, :through => :likes, :source => :thing
    end
    
    class Like < ActiveRecord::Base
      belongs_to :user
      belongs_to :thing
    end
    
    class Thing < ActiveRecord::Base
      # your original association
      belongs_to :user
    
      # the like associations
      has_many :likes
      has_many :liking_users, :through => :likes, :source => :user
    end
    

提交回复
热议问题