1) Can enum
be used for polymorphic associations well?
class MyModel < ActiveRecord::Base
enum my_status: [:a, :b, :c, :d]
end
class MyModel2 < ActiveRecord::Base
enum my_status: [:aa, :bb, :cc, :dd]
end
Any downsides?
2) Can I override getter or setter for enum and how?
I'm assuming MyModel
and MyModel2
are two possible types of a polymorphic association.
Having the same attribute name with different behavior is what polymorphism is good at, I don't see any reason not to use it for this.
Enum attributes can have their getters and setters overwritten just like any attribute.
For example:
# Return the status as uppercase
def my_status
super.upcase
end
# Save status as lowercase
def my_status=(new_status)
super(new_status.downcase)
end
The special methods added by the enum macro can be overridden in the same way.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.