Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: In Rails how to use the model’s Attribute API on a tableless model

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.

like image 380
MintDeparture Avatar asked Apr 09 '19 17:04

MintDeparture


People also ask

What is ActiveModel :: model?

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 in Ruby on Rails?

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.

What is ORM in Ruby on Rails?

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.

What is ActiveRecord base?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.


1 Answers

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.

like image 88
max Avatar answered Oct 01 '22 22:10

max