Home > Blockchain >  Create a model based on a query instead of a table
Create a model based on a query instead of a table

Time:06-22

As a first approximation, I would like to know if it would work to define a rails model based on a database view instead of a real table.

Of course, I want to use that model only to query and not to insert or update.

If that's possible, is it necessary to define the view? Can I instead specify somehow a query (so I do not need to actually create the view).

CodePudding user response:

Considering the view already exists and the database.yml configuration is set correctly (i.e. the view is somehow inside the database you defined there) and its name is View.

The model:

# view.rb
def View < ApplicationRecord
   self.primary_key = 'id'
end

Then you can query like:

View.where(column_name: 'value')
  • Related