Modeling Favorites

I want to add a model Favoriteto my models Userand Link.

Business logic

  • Users can have multiple links (that is, they can add multiple links)
  • Users can use several selected links (their or other users).
  • The link can be approved by several users, but has one owner

I am confused about how to model this association and how will a custom favorite be created after the models are in place?

class User < ActiveRecord::Base
  has_many :links
  has_many :favorites
end

class Link < ActiveRecord::Base
  belongs_to :user
  #can be favorited by multiple users 
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :link 
end
+5
source share
1 answer

How about the following data model:

class User < ActiveRecord::Base
  has_many :links
  has_many :favorites, :dependent => :destroy
  has_many :favorite_links, :through => :favorites, :source => :link
end

class Link < ActiveRecord::Base
  belongs_to :user
  has_many   :favorites, :dependent => :destroy
  has_many   :favorited, :through => :favorites, :source => :user
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :link
end

User , links, Link users, has_many :through (, User has_many :links, :through => :favorites ). , Rails , source.

:

# Some users
user1 = User.create :name => "User1"
user2 = User.create :name => "User2"

# They create some links
link1_1 = user1.links.create :url => "http://link1_1"
link1_2 = user1.links.create :url => "http://link1_2"
link2_1 = user2.links.create :url => "http://link2_1"
link2_2 = user2.links.create :url => "http://link2_2"

# User1 favorites User2 first link
user1.favorites.create :link => link2_1
# User2 favorites both of User1 links
user2.favorites.create :link => link1_1
user2.favorites.create :link => link1_2

user1.links          => [link1_1, link1_2]
user1.favorite_links => [link2_1]
user2.links          => [link2_1, link2_2]
user2.favorite_links => [link1_1, link1_2]
link1_1.favorited    => [user2]

link2_1.destroy

user1.favorite_links => []
user2.links          => [link2_2]
+8

All Articles