peter
peter

Reputation: 42192

activerecord class from custom sql query

Is it possible to create an activerecord class from a custom sql query or view ? It doesn't need to be editable. example:

class c
  select a.*, b.* from a, b where a.code = b.code
end

This example is a join where all the fields from both tables are resent, the one to one joins in activerecord only present fields from one table, the others are accessible through a.bs.fieldname. I would like them aal to be fields on the same level, thus in one class.

so that a.code, a.name and b.code, b.extra can be accessed as c.code, c.name, c.extra

Upvotes: 2

Views: 78

Answers (1)

Dmitry Lihachev
Dmitry Lihachev

Reputation: 504

ActiveRecord will works with your views as with tables. So, firstly create custom view for your things

CREATE VIEW some_things AS (select a.*, b.* from a, b where a.code = b.code)

And then make ActiveRecord based class for accessing them (app/models/some_thing.rb)

class SomeThing < ActiveRecord::Base
end

You can access to your things as like as any other AR objects

p SomeThing.where(code: 'xxx-yyy').order(:name).limit(10).all

Upvotes: 1

Related Questions