I usually include ActiveModel::Model into some PORO (for example for a FormObject::SignUp). I've read about the new Rails 5 ActiveRecord::Attribute API, and I thought I will be able to use it for simpler casting, but not luck.
For example, given
class FormObject::SignUp
include ActiveRecord::Model
include ActiveRecord::Attributes
attribute :birthday, :date
validates :birthday, presence: true
end
I got an NameError: undefined local variable or method `reload_schema_from_cache' for FormObjects::SignUp:Class
exception when I try to instantiate it.
It is not expected to be used standalone? Thanks
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending. Edit: as Mike points out, in this case ActiveRecord is a module... ActiveRecord is defined as a module in Rails, github.com/rails/rails/tree/master/activerecord/lib/…
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
This is now possible in Rails 5.2.
As of Rails 5.2 (#30985), ActiveModel::Atrributes is now available to use in POROs (at least POROs that include ActiveModel::Model)...
Utilizing the gem ActiveModelAttributes
is the only easy way I've been able to find to do this. Depending on your use case, it will probably make sense to use that gem or take a different approach.
Here is the gem: https://github.com/Azdaroth/active_model_attributes
Side note: I got feedback that link-only answers can disappear. If this link disappears, then this answer does indeed become invalid since that will likely mean the gem dosen't exist anymore.
ActiveModel::Attributes
is available as of Rails 5.2 (PR).
Try this:
class FormObject::SignUp
include ActiveModel::Model
include ActiveModel::Attributes
attribute :birthday, :date
validates :birthday, presence: true
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With