如何创建Rails 5模型,实际上是在旅途中创建的数据库视图?

时间:2018-07-22 12:14:46

标签: ruby-on-rails

我正在阅读这篇文章:https://www.salsify.com/blog/engineering/eager-loading-calculations-database-views-in-rails

我非常喜欢创建模型的概念,该模型实际上是对另一个模型的查询,以便创建一些计算。

目前我想做的很简单,对于每个Tag,我都希望获得TagVisits并汇总visits属性。

代码如下:

Events.findOneAndUpdate(
  { _id: req.params.idas, comments: { $elemMatch: { user: req.params.commentID } } },
  { $push: { "comments.$.likes": { user: req.params.id } } }
)

当我直接在Postico中粘贴在class TagVisitSummary < ApplicationRecord belongs_to :tag default_scope { set_from_clause } def ==(other) self.class == other.class && attributes == other.attributes end alias :eql? :== def hash attributes.hash end private def self.set_from_clause query = TagVisit.select(:tag_id).group(:tag_id).select('SUM(visits) as total_visits').all from("(#{query.to_sql}) AS #{table_name}") end def self.columns cols = [ActiveRecord::ConnectionAdapters::Column.new('tag_id', nil, :integer)] cols << ActiveRecord::ConnectionAdapters::Column.new("total_visits", nil, :integer) cols end end 中生成的SQL时,我可以准确地看到所需的结果。不幸的是,运行set_from_clause不会产生任何结果(也不会产生错误)。因此,我怀疑TagVisitSumamry.all方法是否正确。该示例在Rails 4中,我正在使用5。是否有一些更改需要我更改此方法?

谢谢

1 个答案:

答案 0 :(得分:1)

您尝试过吗,风景优美? https://github.com/thoughtbot/scenic

它有助于创建数据库视图和实例化视图,您可以将它们用作ActiveRecord模型。