Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you model "Likes" in rails?

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) an Object can have many likes (from different users)

So I want to be able to do something like this:

User.likes = list of objects liked by a user

Objects.liked_by = list of Users liked by object

The model below is definitely wrong...

class User < ActiveRecord::Base
  has_many :objects
  has_many :objects, :through => :likes
end

class Likes < ActiveRecord::Base
  belongs_to :user
  belongs_to :object
end

class Objects < ActiveRecord::Base
  belongs_to :users
  has_many :users, :through => :likes    
end
like image 909
user1099123 Avatar asked Aug 14 '12 03:08

user1099123


2 Answers

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
like image 100
severin Avatar answered Oct 11 '22 17:10

severin


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.)

like image 22
Michelle Tilley Avatar answered Oct 11 '22 16:10

Michelle Tilley