-
Notifications
You must be signed in to change notification settings - Fork 85
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to model polymorphic types #58
Comments
Hi @kaelumania! It's not possible right now: there is no way to build polymorphic types and let gem know how to decide what type should be used. It could work like this (we define polymorphic type and use it in model): # regular model definition
class Product < ApplicationRecord
attribute :configuration, Configuration.to_array_type
end
class ConfigurationV1
include StoreModel::Model
# ...
end
class ConfigurationV2
include StoreModel::Model
# ...
end
class Configuration
include StoreModel::PolymorphicModel
def self.resolve(json)
json[:version] == '1' ? ConfigurationV1 : ConfigurationV2
end
end In order to add the support we need to implement Please let me know if you want to try it out and I'll be happy to help 🙂 |
Thanks for the fast response :) it don't have to be an array type though. I would suggest to use the same naming as for single table inheritance in active record # regular model definition
class Product < ApplicationRecord
attribute :configuration, Configuration.to_type, polymorphic: true
end
class ConfigurationV1 < Configuration
# ...
end
class ConfigurationV2 < Configuration
# ...
end
class Configuration
def self.resolve(json)
find_subclass(json[:type])
end
end |
Yeah, it definitely should work with a singular associations too. class Product < ApplicationRecord
attribute :configuration, StoreModel.polymorphic { |json| "#{json.type}".constantize }
end |
Added in #61 |
I have a type X and X has one Y, but Y can be Y1 or Y2 or Y3, and each of them has different attributes, but they all subclass Y_base
The text was updated successfully, but these errors were encountered: