I am trying to call a class method from an instance, e.g. @item = @item.class.find(params[:id]) or @item = @item.type.find(params[:id]) @Item can reference objects form different classes. With either of the above examples I get: undefined method `find' for NilClass:Class Any help?
on 2007-02-05 22:20
on 2007-02-05 22:27
I don't know that it is the best way, but you can do this with eval. Eval will take a string and interpret it as ruby code. So you would do something like: eval( @item.class + '.find(params[:id])' ) So this should take your class name, append the find clause and then run the result.
on 2007-02-05 22:38
Ok I tried eval( @item.class.to_s + '.find(params[:id])' ) and i still get the error undefined method `find' for NilClass:Class error.
on 2007-02-05 22:40
stupid mistake by me I think I know the problem, i'll post again when i'm sure.
on 2007-02-05 22:56
I got it working with, @item = @items.pop.type.find(params[:id]) I just wasn't initializing@item with anything. Thanks monki for the eval hint though. I wasn't aware of the eval usage.
on 2007-02-05 23:03
Good to know, I guess I overlooked the simple answer. Your way is better, as eval will blindly do whatever you tell it (which can be dangerous).
on 2007-02-06 10:07
Your original method was better (IMHO) -- @item.class.find(params[:id]) -- as type is deprecated and can sometimes behave unexpectedly as it's used as the key in STI models. Also wanted to check you knew that @items.pop is a destructive method, i.e. the item is removed from @items. I would wonder if @items.last.class.find(params[:id]) is perhaps a bit cleaner. You've prob figured now that undefined method `find' for NilClass:Class was happening because @item was nil (instance variables are nil when they are undefined, unlike local variables -- try p @item and p item in the console), and the class of nil is NilClass, which obviously doesn't have a find method. HTH Chris