How do you model “Likes” in rails?

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

    Models & associations as per naming conventions of rails modeling

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

    Also, you can use of already built-in gems like acts-as-taggable-on to have same functionality without code :)

提交回复
热议问题