So I’m using MongoDB in an app and the fields for my documents have grown but In my views I don’t want to have to have like an if block for each attribute, how can I have rails just display the value of the attribute if it is exists otherwise just quietly do nothing?
Example:
Since Mongo is schema-less these values wouldn’t be defined in earlier instances of my models.
<%= @company.address %>
<%= @company.longitude %>
<%= @company.latitude %>
How do I handle this?
If you want it to just cope, you can always implement your own
method_missingon that class which just eats calls and returnsnil:This could sweep a number of problems under the carpet, so you probably want to be careful when doing this sort of thing.
You could also make an extension that lets you do this:
This will return
nilif there is noaddressmethod if you add this in an initializer:The
trymethod that’s part of Rails will only work if a method may returnnil, but not if the method is not defined.