建模收藏夹

时间:2011-11-23 02:40:24

标签: ruby-on-rails ruby database ruby-on-rails-3

我希望将Favorite模型添加到我的UserLink模型中。

业务逻辑

  • 用户可以拥有多个链接(也就是说,他们可以添加多个链接)
  • 用户可以喜欢多个链接(自己或其他用户)
  • 链接可以被多个用户收藏,但拥有一个所有者

我对如何建模这种关联以及如何在模型到位后创建用户喜好感到困惑?

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

1 个答案:

答案 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]