How do you model “Likes” in rails?

前端 未结 4 1599
太阳男子
太阳男子 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:13

    You are close; to use a :through, relation, you first must set up the relationship you're going through:

    class User < ActiveRecord::Base
      has_many :likes
      has_many :objects, :through => :likes
    end
    
    class Likes < ActiveRecord::Base
      belongs_to :user
      belongs_to :object
    end
    
    class Objects < ActiveRecord::Base
      has_many :likes
      has_many :users, :through => :likes    
    end
    

    Note that Objects should has_many :likes, so that the foreign key is in the right place. (Also, you should probably use the singular form Like and Object for your models.)

提交回复
热议问题