Rails model without database
I think the blog post you are linking is the best way to go. I would only suggest moving the stubbed out methods into a module not to pollute your code.
Active Record without database
Take a look at ActiveModel. That's what AR uses under the hood.
Set non-database attribute for rails model without `attr_accessor`
This is expected because it's how ActiveRecord works by design. If you need to set arbitrary attributes, then you have to use a different kind of objects.
For example, Ruby provides a library called OpenStruct
that allows you to create objects where you can assign arbitrary key/values. You may want to use such library and then convert the object into a corresponding ActiveRecord instance only if/when you need to save to the database.
Don't try to model ActiveRecord
to behave as you just described because it was simply not designed to behave in that way. That would be a cargo culting error from your current PHP knowledge.
Use Rails model without database interaction
Look into ActiveModel
E.g. specifically for validations (taken from the above docs)
class Person
include ActiveModel::Validations
attr_accessor :first_name, :last_name
validates_each :first_name, :last_name do |record, attr, value|
record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
end
end
person = Person.new
person.first_name = 'zoolander'
person.valid? # => false
Adding fields to a Rails model without saving them in the database in Rails
If you want to read and write the accessors use attr_accessor
:
class Event < ActiveRecord::Base
attr_accessor :duration, :datatime
end
You do not need to include ActiveModel::AttributeMethods
to utilize attr_accessor
.
To include the accessors in the JSON tell render to include them:
render json: events, methods: [:duration, :datatime]
Rails 4 - Validate Model without a database
you have to declare them as attributes.
attr_accessor :name, email, :phone, :comment
Existing Rails model without fetching it from the database
I solved the problem by doing the following.
Create a new model class which extends the model class that I want to have cached into memory.
Set the table_name of the new class to the same one as the parent class.
Create a new initialize method, call the super method in it, and then allow a parameter of that method to allow for a hash variable containing all the properties of the parent class.
Overload the method
new_record?
and set that tofalse
so that the associations work.
Here's my code:
class Session < User
self.table_name = 'users'
METHODS = [:id, :username] # all the columns that you wish to have in the memory hash
METHODS.each do |method|
attr_accessor method
end
def initialize(data)
super({})
if data.is_a?(User)
user = data
data = {}
METHODS.each do |key|
data[key] = user.send(key)
end
else
data = JSON.parse(data)
end
data.each do |key,value|
key = key.to_s
self.send(key+'=',value)
end
end
def new_record?
false
end
end
ActiveRecord::Base Without Table
This is an approach I have used in the past:
In app/models/tableless.rb
class Tableless < ActiveRecord::Base
def self.columns
@columns ||= [];
end
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
# Override the save method to prevent exceptions.
def save(validate = true)
validate ? valid? : true
end
end
In app/models/foo.rb
class Foo < Tableless
column :bar, :string
validates_presence_of :bar
end
In script/console
Loading development environment (Rails 2.2.2)
>> foo = Foo.new
=> #<Foo bar: nil>
>> foo.valid?
=> false
>> foo.errors
=> #<ActiveRecord::Errors:0x235b270 @errors={"bar"=>["can't be blank"]}, @base=#<Foo bar: nil>>
Related Topics
How to Calculate Number of Chars Common to Two Strings
Ruby Class Instance Variable Vs. Class Variable
What Is the Best Method of Handling Currency/Money
How to Create Multiple Submit Buttons For the Same Form in Rails
What Does @@Variable Mean in Ruby
Using Rails Serialize to Save Hash to Database
Incompatible Character Encodings: Ascii-8Bit and Utf-8
Case Statement With Multiple Values in Each 'When' Block
Class ≪≪ Self Idiom in Ruby
Pg::Connectionbad - Could Not Connect to Server: Connection Refused
Redirect_To Using Post in Rails
In Ruby on Rails, How to Format a Date With the "Th" Suffix, as In, "Sun Oct 5Th"
Ruby Multiline Block Without Do End
Rails Has_Many :Through Find by Extra Attributes in Join Model