Rails: how database view works with active records

265 views Asked by At

I'm new in Rails. In one source code, I see that someone create some rake tasks related to create view. For example:

desc 'create statistic data'
task create_product_statistics:  do
  ActiveRecord::Base.connection.execute <<-SQL
    CREATE VIEW product_statistics AS
      // some complex sql query
  SQL
end

As I see in all project, I have a table named ProductStatistic. That's all. Because there isn't any document about this as I searched, so I don't know how does above code map to rails code base. Please let me know how create database view affects to active record query. Is that look like active record see database view as normal table?

Thanks

1

There are 1 answers

0
Eyeslandic On BEST ANSWER

You can use a view just like any other table like this.

class ProductStatistics < ApplicationRecord
  self.table_name = 'product_statistics'
end

... in some controller
ProductStatistics.where(....)