I have many types of vehicles, all having their respective brands. Each vehicle has one brand. And in this scenario below, I'm trying to figure out how to get .brandable_type to be equal to .type
How do I return base_class with type Vehicle::Car?
Console:
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'
Migrations:
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
Models:
# 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