查询中的虚拟属性 [英] virtual attribute in a query
问题描述
用户模型具有 all_scores 属性,我在下面创建了方法
User model has all_scores attribute and i created the method below
models/user.rb
models/user.rb
def score
ActiveSupport::JSON.decode(self.all_scores)["local"]
end
我正在尝试使用此虚拟属性得分来过滤用户的操作.例如:我需要分数超过50的用户.问题是我不能在查询中使用虚拟属性作为常规属性.
What i'm trying to do this using this virtual attribute score to filter users. For example: I need the users whose score is over 50. The problem is i can't use virtual attribute as a regular attribute in a query.
User.where("score > 50") # i can't do this.
任何帮助将不胜感激.
推荐答案
最简单"的解决方案可能是 User.all.select {| user |user.score>50}
.显然,将每个用户记录从数据库中拉出是非常低效的.
Well, the "easiest" solution would probably be User.all.select{|user| user.score > 50}
. Obviously that's very inefficient, pulling every User record out of the database.
如果要查询涉及分数的信息,为什么不将 score
列添加到users表?每当更改 all_scores
时,您都可以对其进行更新.
If you want to do a query involving the score, why don't you add a score
column to the users table? You could update it whenever all_scores
is changed.
class User < AR::Base
before_save :set_score, :if => :all_scores_changed?
protected
def set_score
self.score = ActiveSupport::JSON.decode(self.all_scores)["local"] rescue nil
end
end
这还将避免每次访问 user#score
时都不断反序列化JSON数据.
This will also avoid constantly deserializing JSON data whenever you access user#score
.
这篇关于查询中的虚拟属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!