I'm trying to send the count on an active Record object's association to the redis-object gem
class Post > ActiveRecord::Base
has_many :comments
include Redis::Objects
value :redis_comment_count, :default => self.comments.count
end
PS: setting :default => "string" works just fine
but this does not work because self at that place in the code (its not in a method definition) refers to the class definition of Post and not a post instance itself. I was trying to figure out if this was something that was even possible to do.
Am I making sense?
Have you tried?
value :redis_comment_count, default: -> { self.comments.count}
That's using Ruby 1.9's new hash syntax along with the 'stab' or lambda operator .
Unfortunately, it looks like you will have to go the longer way of setting up save callbacks for your comments. I browsed through the gem and it doesn't look like passing a proc for calling later is supported yet (see here ).
By the way :
Besides the fact that you are calling the class method and not the instance method, self.comments.count
is evaluated when the class is loaded, right there when you call:
value :redis_comment_count, :default => self.comments.count
# This becomes:
# value :redis_comment_count, :default => 1 # Example
and not every time that the redis-objects gem uses value_options[:default]
.
This value will keep getting re-evaluated if your class keeps getting reloaded, as in the case of the default setup for the development environment. However, in the production environment where we usually have cache_classes
enabled, this value will be evaluated only whenever the Rails application boots up and loads your models.
Passing a proc would work if this were supported.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.