如何在Rails 5中添加实例化视图

时间:2018-08-13 08:21:38

标签: ruby-on-rails sqlite materialized

我想为平均评级添加实例化视图。

我的费率模型是:

project(profiling)

if(ANDROID)
    include_directories(${ANDROID_SYSROOT}/usr/include)
    message(STATUS "Including ${ANDROID_SYSROOT}/usr/include")
endif()

set(profiling_SRCS
  profiling.cpp
  )

set(profiling_HEADERS
  profiling.h
  )

add_library(profiling STATIC ${profiling_SRCS} ${profiling_HEADERS})

我的帖子模型是:

class Rating < ApplicationRecord
  belongs_to :post
  validates_presence_of :rate
  validates_inclusion_of :rate,in: 1..5
end

我想为使用物化视图为的帖子查找平均

class Post < ActiveRecord::Base
  has_many :ratings
  accepts_nested_attributes_for :ratings
end

我为MV创建了迁移

<%= "Avg.rate:#{post.ratings.average(:rate).to_f.round(2)}"%><br>

我发现类似的问题

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

1 个答案:

答案 0 :(得分:0)

SQLite不支持实例化视图。请在此处How can a materialized view be created in sqlite?

阅读更多内容

您必须切换到其他RDMS(例如PostgreSQL)或创建“普通”表并使用trigger对其进行更新。