Ruby on rails 在多态表中获取STI类型
我有很多类型的车辆,都有各自的品牌。 每辆车都有一个品牌。在下面的场景中,我试图找出如何使.brandable_type等于.type 如何返回类型为车辆::汽车的基本类?Ruby on rails 在多态表中获取STI类型,ruby-on-rails,ruby-on-rails-4,polymorphic-associations,single-table-inheritance,Ruby On Rails,Ruby On Rails 4,Polymorphic Associations,Single Table Inheritance,我有很多类型的车辆,都有各自的品牌。 每辆车都有一个品牌。在下面的场景中,我试图找出如何使.brandable_type等于.type 如何返回类型为车辆::汽车的基本类? 控制台: vehicle = Vehicle.create(name: 'Mustang GT', type: 'Vehicle::Car') vehicle.create_brand!(name: 'Ford') Vehicle.find_by(name: 'Mustang GT').brand #retu
控制台:
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
class CreateVehicles
型号:
# 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
#app/models/vehicle.rb
类别车辆
您忽略了通过:brandable
将车辆链接到品牌:
class Vehicle < ActiveRecord::Base
has_one :brand, as: :brandable
end
class车辆
此外,我认为你的关联是不对的,除非你有特定的理由这样设置,因为品牌和车辆听起来应该是一对多的关系,一个品牌可能有很多车辆,而不是一个品牌属于一对一关联的车辆,一般来说,任何食物都可以。至于协会。实际上,我把它命名为“has_one:brand,class_name:brand,as::brandable”。。。但我仍然得到相同的结果。Brand.brandable_类型返回车辆。。。不是车辆::CarAli,也是为了回答你关于这段关系的问题。从整个范围来看,考虑到这个项目背后的逻辑,我们选择沿着这条路走下去