virtual attribute in a query

泪湿孤枕 提交于 2021-02-11 01:55:16

问题


User model has all_scores attribute and i created the method below

models/user.rb

def score
  ActiveSupport::JSON.decode(self.all_scores)["local"]
end

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.

Any help will be appreciated.


回答1:


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.

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

This will also avoid constantly deserializing JSON data whenever you access user#score.



来源:https://stackoverflow.com/questions/6926125/virtual-attribute-in-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!