问题
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