Ruby on Rails: a fully functional model without tables

After searching for an example table without tables, I came across this code, which seems to be a general consensus on how to create it.

class Item < ActiveRecord::Base class_inheritable_accessor :columns self.columns = [] def self.column(name, sql_type = nil, default = nil, null = true) columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null) end def all return [] end column :recommendable_type, :string #Other columns, validations and relations etc... end 

However, I would also like it to function as a model, presenting a collection of an object, so that I can do Item.all.

The plan is to populate the elements with files, and each property element will be extracted from the files.

However, for now, if I do Item.all, I get

Mysql2::Error Table 'test_dev.items' doesn't exist...

error.

+4
source share
2 answers

I found an example at http://railscasts.com/episodes/219-active-model where I can use model functions and then override static methods like everyone else (should have thought of this before).

 class Item include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :name, :email, :content validates_presence_of :name validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i validates_length_of :content, :maximum => 500 class << self def all return [] end end def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def persisted? false end end 
+7
source

Or you can do it like this (Edge Rails only):

 class Item include ActiveModel::Model attr_accessor :name, :email, :content validates_presence_of :name validates_format_of :email, :with => /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i validates_length_of :content, :maximum => 500 end 

Just by enabling ActiveModel :: Model, you will get all the other modules included for you. It provides a cleaner and more explicit view (since it is an ActiveModel)

+4
source

Source: https://habr.com/ru/post/1339742/


All Articles