【问题标题】:Getting STI type in polymorphic table在多态表中获取 STI 类型
【发布时间】: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

【问题讨论】:

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


【解决方案1】:

您省略了通过:brandable 将车辆与品牌相关联:

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

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

【讨论】:

  • 一个品牌也可以存在于服装、食品任何一般事物上。至于协会。我实际上将其命名为“has_one :brand, class_name: Brand, as: :brandable” ...但我仍然得到相同的结果。
  • Brand.brandable_type 返回 Vehicle... 而不是 Vehicle::Car
  • 阿里,也回答你关于关系的问题。从整个范围来看,考虑到这个项目背后的逻辑,我们选择走这条路
猜你喜欢
  • 1970-01-01
  • 2016-05-21
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
相关资源
最近更新 更多