0

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
levelone
  • 2,289
  • 3
  • 16
  • 17
  • possible duplicate of [STI and polymorphs](http://stackoverflow.com/questions/2603600/sti-and-polymorphs) – Doguita Oct 24 '14 at 11:38

1 Answers1

0

You have omitted linking the Vehicle to the Brand through :brandable:

class Vehicle < ActiveRecord::Base 
  has_one :brand, as: :brandable
end

Additionally I think your association is not right, unless you have a specific reason to set it up like this, because Brand and Vehicle sound like they should have a 1-to-many relationship, it is more likely that a Brand can have many Vehicles than a Brand belongs to a Vehicle with 1-to-1 association

Alireza
  • 2,641
  • 17
  • 18
  • A brand can also exist for clothing, food anything in general. As for the association. I actually had it as "has_one :brand, class_name: Brand, as: :brandable" ... But I still get the same result. – levelone Oct 24 '14 at 11:22
  • Brand.brandable_type returns Vehicle... not Vehicle::Car – levelone Oct 24 '14 at 11:23
  • Ali, also to answer also your question about the relationship. By the look of the entire scope we chose to go down this path considering the logic behind this project – levelone Oct 24 '14 at 11:30