开发者

virtual attribute in a query

开发者 https://www.devze.com 2023-03-25 18:43 出处:网络
User model has all_scores attribute and i created the method below models/user.rb def score ActiveSupport::JSON.decode(self.all_scores)[\"local\"]

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 ove开发者_StackOverflow社区r 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消