Pregunta

In my Rails model I have a description method:

def description
  if self.channels.nil?
    return self.allowed_ip_addresses
  else
    return self.channels.to_s + ' channels - ' + self.allowed_ip_addresses
  end
end

I have quite a few models where I created a description method which returns some useful info based on the other properties of that model.

The problem I have just realised is that this model in particular has a description column in it's table so I was just wondering the best way to solve this, I've looked around but not found anything useful.

The first thing I thought of was to pass an argument when calling description, e.g.

def description(table_value = 0)
  if table_value
    return self.description
  end

  if self.channels.nil?
    return self.allowed_ip_addresses
  else
    return self.channels.to_s + ' channels - ' + self.allowed_ip_addresses
  end
end

but soon realised that this is pointless since it will just call the description method recursively and die (assuming a 1 is passed with the call to description).

I could also change the table column name but it's used elsewhere so I'm just trying to see if there is an alternative solution.

¿Fue útil?

Solución 2

Ruby has the concept of "super" which lets you call methods in parent classes or modules. In Rails, Active Record lets you take advantage of this by overriding the "column method" and still get to the database value by calling super. It's not really clear from your question under what conditions you want to use the database value and when you want to use the custom logic. Here's some pseudo code to get you started though:

def description
  return super if Use Database Value?

  if self.channels.nil?
    return self.allowed_ip_addresses
  else
    return self.channels.to_s + ' channels - ' + self.allowed_ip_addresses
  end
end

Otros consejos

I would definitely rename your custom description method.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top