我希望将Favorite
模型添加到我的User
和Link
模型中。
业务逻辑
我对如何建模这种关联以及如何在模型到位后创建用户喜好感到困惑?
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
答案 0 :(得分:8)
以下数据模型如何:
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's first link
user1.favorites.create :link => link2_1
# User2 favorites both of User1's 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]