I have a table-less model like this:
class SomeModel
include ActiveModel::Model
attribute :foo, :integer, default: 100
end
I’m trying to use an attribute from the link below, it works perfectly in normal models however I cannot get it to work in a tableless model.
https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html
This causes an undefined
I’ve tried adding active record attributes:
include ActiveRecord::Attributes
as an include too however this causes a different error related to the schema.
How do I go about using the attribute in a tableless model? Thanks.
ActiveModel::Model allows implementing models similar to ActiveRecord::Base . class EmailContact include ActiveModel::Model attr_accessor :name, :email, :message validates :name, :email, :message, presence: true def deliver if valid? #
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.
Object Relational Mapping, commonly referred to as its abbreviation ORM, is a technique that connects the rich objects of an application to tables in a relational database management system.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
You need to include ActiveModel::Attributes
class SomeModel
include ActiveModel::Model
include ActiveModel::Attributes
attribute :foo, :integer, default: 100
end
For some reason its not included in ActiveModel::Model
. This internal API was extracted out of ActiveRecord in Rails 5 so you can use it with table-less models.
Note that ActiveModel::Attributes
is NOT the same thing as ActiveRecord::Attributes
. ActiveRecord::Attributes
is a more specialized implementation that assumes the model is backed by a database schema.
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