Trần Kim Dự
Trần Kim Dự

Reputation: 6102

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

Upvotes: 0

Views: 301

Answers (1)

Eyeslandic
Eyeslandic

Reputation: 14900

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

Upvotes: 1

Related Questions