在多态表中获取STI类型

时间:2014-10-24 04:31:04

标签: ruby-on-rails ruby-on-rails-4 polymorphic-associations single-table-inheritance

我有很多类型的车辆,都有各自的品牌。 每辆车都有一个品牌。在下面的这个场景中,我试图弄清楚如何让.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

1 个答案:

答案 0 :(得分:0)

您已省略通过:brandable

将车辆与品牌相关联
class Vehicle < ActiveRecord::Base 
  has_one :brand, as: :brandable
end

另外我认为你的关联是不对的,除非你有特别的理由将它设置为这样,因为Brand和Vehicle听起来应该有一对多的关系,品牌更有可能拥有许多车辆而非品牌属于具有1对1关联的车辆