【发布时间】:2014-10-24 04:31:04
【问题描述】:
我有很多类型的车辆,都有各自的品牌。 每辆车都有一个品牌。在下面的这种情况下,我试图弄清楚如何让 .brandable_type 等于 .type
如何返回 Vehicle::Car 类型的 base_class?
控制台:
vehicle = Vehicle.create(name: 'Mustang GT', type: 'Vehicle::Car')
vehicle.create_brand!(name: 'Ford')
Vehicle.find_by(name: 'Mustang GT').brand #returns brand
Brand.find_by(name: 'Ford').brandable_type #returns 'Vehicle' not 'Vehicle::Car'
迁移:
class CreateVehicles < ActiveRecord::Migration
def change
create_table :vehicles do |t|
t.string :name
t.string :type
t.timestamps
end
add_index :vehicles, [:id, :type]
end
end
class CreateBrands < ActiveRecord::Migration
def change
create_table :brands do |t|
t.integer :brandable_id
t.string :brandable_type
t.string :name
t.timestamps
end
add_index :brands, [:brandable_id, :brandable_type]
end
end
型号:
# app/models/vehicle.rb
class Vehicle < ActiveRecord::Base
has_one :brand, class_name: Brand, as: :brandable
end
# app/models/vehicle/car.rb
class Vehicle::Car < Vehicle
end
# app/models/vehicle/bicycle.rb
class Vehicle::Bicycle < Vehicle
end
# app/models/brand.rb
class Brand
belongs_to :brandable, polymorphic: true
def brandable_type=(sType)
super(sType.to_s.classify.constantize.base_class.to_s)
end
end
【问题讨论】:
-
STI and polymorphs 的可能重复项
标签: ruby-on-rails ruby-on-rails-4 polymorphic-associations single-table-inheritance