0

I am using AwesomeNestedSet and have a place in my app that calls the parent method on a model instance. In some cases, parent returns nil. That's fine but in the cases where it does I need it to return a string of root instead.

I have this scenario in 3 places across my app so want a centralised place I can write this. In my Category model I did try:

def parent parent || 'root' end 

But of course that just gets everything into a loop.

How can I get this functionality but without causing it to loop?

Neil

0

1 Answer 1

2

This should do the trick:

def parent super || 'root' end 
Sign up to request clarification or add additional context in comments.

5 Comments

This works perfectly! Apologies for the delay. If, I wanted to, (using your solution), also access, parent on the instance but without calling our new overidden version. How could I do that?
I'm trying to figure out how to do that, but it may be impossible. That is the idea of an override after all. Maybe you could explain a bit more about why you'd like to do that, or what you're trying to accomplish? That might make things clearer. It's possible something could be done with aliasing methods, but I'd need to know more.
@benfenner I have the following method: def previous_names super.split " | " if super end but, I need a way to check if the "previous_names" field in the database is filled in, in a view before I can try to split it using the method. Does that make sense?
@rctneil I am sort of following you I think. Aside from how awful it would be to load up a view with all this logic, would this (or something like it) accomplish what you're trying to do? <%= @category_instance.previous_names&.split(' | ') || '[no previous names]' %>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.