【发布时间】:2013-10-28 09:51:19
【问题描述】:
我想在 Rails4 应用程序中创建动态关联。
我有以下型号:
class Pilot < ActiveRecord::Base
has_many :cars
end
class Cars < ActiveRecord::Base
belongs_to :pilot
end
汽车有一个属性颜色,我想创建与可用颜色一样多的关联
例如,如果我有 1 辆红色汽车、2 辆蓝色汽车和 1 辆绿色汽车,我想在我的试点模型中使用
has_many :red_cars
has_many :blue_cars
has_many :green_cars
关键是我不知道会被拾取的颜色。
可以实现吗?
谢谢。
更新
我想我可能会做类似的事情
#untested. Written just now
Car.all.map(&:color).uniq.each do |color|
has_many "#{color}_cars".to_sym, -> { where(color: '#{color}') }, class_name: 'Car'
end
如果没有更好的可能。
【问题讨论】:
标签: associations ruby-on-rails-4