我正在尝试创建一个系统,我的网站的用户可以在其中收藏页面.这些页面有两种类型,俱乐部或体育.所以,我有四个模型,相关联:
用户模型:
class User < ActiveRecord::Base
..
has_many :favorites
has_many :sports, :through => :favorites
has_many :clubs, :through => :favorites
..
end
Run Code Online (Sandbox Code Playgroud)
收藏夹型号:
class Favorite < ActiveRecord::Base
..
belongs_to :user
belongs_to :favoritable, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)
俱乐部型号:
class Club < ActiveRecord::Base
..
has_many :favorites, :as => :favoritable
has_many :users, :through => :favorites
def to_param
slug
end
end
Run Code Online (Sandbox Code Playgroud)
运动模特:
class Sport < ActiveRecord::Base
..
def to_param
slug
end
..
has_many :favorites, :as => :favoritable
has_many :users, :through => :favorites
..
end
Run Code Online (Sandbox Code Playgroud)
从本质上讲,用户可以通过收藏夹进行体育或俱乐部,而收藏,体育和俱乐部之间的关联是多态的. …
model ruby-on-rails polymorphic-associations model-associations rails-admin