如何在 rails 5 中添加物化视图
How to add Materialized Views in rails 5
我想为平均评分添加物化视图。
我的费率模型是:
class Rating < ApplicationRecord
belongs_to :post
validates_presence_of :rate
validates_inclusion_of :rate,in: 1..5
end
我的Post型号是:
class Post < ActiveRecord::Base
has_many :ratings
accepts_nested_attributes_for :ratings
end
我想为post使用物化视图
找到平均值
<%= "Avg.rate:#{post.ratings.average(:rate).to_f.round(2)}"%><br>
我为 MV 创建了一个迁移
class CreateAvgMatView < ActiveRecord::Migration[5.1]
def change
execute <<-SQL
CREATE MATERIALIZED VIEW rateavg_matview AS
SELECT AVG("ratings"."rate") FROM "ratings"
SQL
end
end
我发现了一个类似
的问题
D013:post_app naren$ rake db:migrate
== 20180813080437 CreateAvgMatView: migrating =================================
-- execute(" CREATE MATERIALIZED VIEW rateavg_matview AS\n SELECT AVG(\"ratings\".\"rate\") FROM \"ratings\"\n\n")
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: near "MATERIALIZED": syntax error: CREATE MATERIALIZED VIEW rateavg_matview AS
SELECT AVG("ratings"."rate") FROM "ratings"
SQLite 不支持物化视图。请在此处阅读更多内容 How can a materialized view be created in sqlite?
您必须切换到不同的 RDMS(例如 PostgreSQL)或创建 "normal" table 并使用 trigger 更新它。
我想为平均评分添加物化视图。
我的费率模型是:
class Rating < ApplicationRecord
belongs_to :post
validates_presence_of :rate
validates_inclusion_of :rate,in: 1..5
end
我的Post型号是:
class Post < ActiveRecord::Base
has_many :ratings
accepts_nested_attributes_for :ratings
end
我想为post使用物化视图
找到平均值<%= "Avg.rate:#{post.ratings.average(:rate).to_f.round(2)}"%><br>
我为 MV 创建了一个迁移
class CreateAvgMatView < ActiveRecord::Migration[5.1]
def change
execute <<-SQL
CREATE MATERIALIZED VIEW rateavg_matview AS
SELECT AVG("ratings"."rate") FROM "ratings"
SQL
end
end
我发现了一个类似
的问题D013:post_app naren$ rake db:migrate
== 20180813080437 CreateAvgMatView: migrating =================================
-- execute(" CREATE MATERIALIZED VIEW rateavg_matview AS\n SELECT AVG(\"ratings\".\"rate\") FROM \"ratings\"\n\n")
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: near "MATERIALIZED": syntax error: CREATE MATERIALIZED VIEW rateavg_matview AS
SELECT AVG("ratings"."rate") FROM "ratings"
SQLite 不支持物化视图。请在此处阅读更多内容 How can a materialized view be created in sqlite?
您必须切换到不同的 RDMS(例如 PostgreSQL)或创建 "normal" table 并使用 trigger 更新它。