开发者

Rails STI models with the same name but inheriting from another model

开发者 https://www.devze.com 2023-03-18 14:32 出处:网络
My Rails application uses STI where I have two different types of Customers.One is a Person Customer and the other is a Company Customer.

My Rails application uses STI where I have two different types of Customers. One is a Person Customer and the other is a Company Customer.

So in my People controller I want to instantiate a Customer. (So that the type attribute of a Person is Customer).

My Customer model inherits fro开发者_如何学编程m the Person model. The model filename is called customer.rb In my companies controller I also want to instantiate a Customer, which again uses customer.rb, but this won't work because it inherits from Person still.

How can I use the same model, but each model needs to inherit from another model?

#models/customer.rb
class Customer < Person
end

#models/customer.rb
class Customer < Company
end

I tried moving customer.rb to different directories, e.g. person/, company/ but I'm not sure if this is correct. Maybe I should use modules?


That will not work. You cannot have two distinct classes with the same name, and a class cannot inherit from two classes.

Maybe you can use a polymorphic association between Customer and Person/Company.

class Person
  has_many :customers, :as => :customer_entity
end

class Company
  has_many :customers, :as => :customer_entity
end

class Customer
  belongs_to :customer_entity, :polymorphic => true
end


The reason this won't work is that in the example you gave, the second class definition for Customer will change the inheritance from Person to Company, which is not what you want.

If the polymorphic suggestion won't work for you, another solution would be to create two classes, CustomerPerson and CustomerCompany (i recommend using better names!) and extract out any common functionality to a module and then include/extend it into each class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号