代码之家  ›  专栏  ›  技术社区  ›  Zabba fl00r

Rails ActiveRecord关联“一个或另一个”

  •  1
  • Zabba fl00r  · 技术社区  · 15 年前

    我想知道,在Rails中如何实现这样的关联:

    class Car < ActiveRecord::Base
        belongs_to :person
    end
    
    class Truck < ActiveRecord::Base
        belongs_to :person
    end
    
    class Person < ActiveRecord::Base
        #How to do the association as below?
        has_one :car or :truck
    end
    

    从本质上说,我是想强制 Person 可以吃一个 Car Truck 但不能两者兼得。

    作为第二种,有没有解决方案 可以拥有 许多的 小型车 许多的 卡车 ,但不是两者的混合?

    有什么办法吗?

    1 回复  |  直到 15 年前
        1
  •  3
  •   zetetic    15 年前

    很适合 Single Table Inheritance

    class Vehicle < ActiveRecord::Base
        belongs_to :person
    end
    
    class Car < Vehicle
      # car-specific methods go here
    end
    
    class Truck < Vehicle
      # truck-specific methods go here
    end
    
    class Person < ActiveRecord::Base
        has_one :vehicle
    end
    
    person = Person.new
    person.vehicle = Car.new # (or Truck.new)
    

    问题的第二部分比较棘手。一种方法是对个人也使用继承权:

    class Person < ActiveRecord::Base
        has_many :vehicles
    end
    
    class TruckDriver < Person
      def build_vehicle(params)
        self.vehicles << Truck.new(params)
      end
    end
    
    class CarDriver < Person
      def build_vehicle(params)
        self.vehicles << Car.new(params)
      end
    end