2

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

The drawback of this approach is that most RDBMS systems don't allow an index on a view. This means you're doing a linear scan to find the record you want.
You always can create indexes on source tables for increasing VIEW performance. So, in this case you can create 2 indexes: a(code) and b(code). It will be good idea to add index by a(name) field.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.