ruby-on-railsrubyactiverecorddatabase-view

Rails: how database view works with active records


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


Solution

  • 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(....)