0

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?

concept47
  • 30,257
  • 12
  • 52
  • 74

2 Answers2

0

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.

Community
  • 1
  • 1
Alistair A. Israel
  • 6,417
  • 1
  • 31
  • 40
  • yes. I used the old ruby style of default: lambda { self.comments.count } and that returns a proc, which doesn't work for me, I need it to return the actual value, but when I try lambda { self.comments.count }.call I got the error "NoMethodError: undefined method `comments' for #" when I hit reload! in rails console – concept47 Feb 15 '13 at 06:43
0

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.

kristinalim
  • 3,459
  • 18
  • 27