0

给定模型:

class User
  has_many :cars
  has_many :foods
end

class Car
  belongs_to :user
  has_many :colors, :as => :owner
end

class Food
  belongs_to :user
  has_many :colors, :as => :owner
end

class Color
  belongs_to :owner, :polymorphic => true   # This can be Food or Car
end

我怎么能说在 Rails 3和Rails 3 上都有User很多?那么 Rails 2 呢?ColorCarFood

4

1 回答 1

3

我相信这应该为你做(它应该在 Rails 2 和 Rails 3 中都可以工作):

class User
  has_many :colors
  has_many :cars, :through => :colors, :source => :owner, :source_type => "Car"
  has_many :foods, :through => :colors, :source => :owner, :source_type => "Food"
end

class Color
  belongs_to :user
  belongs_to :owner, :polymorphic => true
end

class Car
  belongs_to :user
  has_many :colors, :as => :owner
end

class Food
  belongs_to :user
  has_many :colors, :as => :owner
end
于 2013-10-22T17:27:51.743 回答