Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the model class from active record relation

I have a Rails model:

class Foo < ActiveRecord::Base
  ...
end

Given an active record relation:

limited_foo = Foo.where(...)

how can I get the original model class?

limited_foo ... # => Foo
like image 420
sawa Avatar asked Apr 18 '17 08:04

sawa


People also ask

What is active record relation?

The Relation Class. Having queries return an ActiveRecord::Relation object allows us to chain queries together and this Relation class is at the heart of the new query syntax. Let's take a look at this class by searching through the ActiveRecord source code for a file called relation.

What do you mean by active record model?

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.

What does active record return?

Creates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

What is Active model in Ruby?

Active Model is a library containing various modules used in developing classes that need some features present on Active Record.


1 Answers

ActiveRecord::Relation has an attribute_reader klass:

limited_foo.klass
#=> Foo

Source is here. Alias model works as well.

like image 138
Ilya Avatar answered Oct 20 '22 22:10

Ilya