Avoiding Nil errors

How do I suppress the nil errors in ActionView Erb templates?

For instance if I have a record in the database table that allows null
fields and then I show the record, in this case an association using
belongs_to, how do I suppress the Nil errors on those fields that are
null?

Thanks,
Phill

If I am understanding your question correctly, this may help:

<%= event.category? event.category.name : ‘No Category Set’ %>

-Bradly

Thanks. That is what I’m looking for. I was wondering though if there
was an simpler / cleaner way than if statements though.

Thanks again,

phill

On Nov 15, 2006, at 21:30 , bluengreen wrote:

Thanks. That is what I’m looking for. I was wondering though if there
was an simpler / cleaner way than if statements though.

<%= event.category.name rescue ‘No Category Set’ %>


Jakob S. - http://mentalized.net

also works:

<%= event.category.name || “default” %>

On 15 Nov 2006, at 22:15, Chris H. wrote:

there
was an simpler / cleaner way than if statements though.

<%= event.category.name rescue ‘No Category Set’ %>

I’ve already used all the different ways described in previous
messages, but there has to be a way of setting a global replacement
string. My views are just littered with code like that and it doesn’t
look nice. A helper might probably help, but even that adds code to
every value in the view.

Best regards

Peter De Berdt

Hey,

As has already been pointed out, you can use ‘rescue’, however I find
that the Law of Demeter [1] helps here.

class Event < ActiveRecord::Base
belongs_to :category

def category_name
self.category and self.category.name or “No Category Name”
end
end

<%= event.category_name %>

Another option is to declare a helper method:

def event_category_name(event)
event.category and event.category.name or “No Category Name”
end

<%= event_category_name(event) %>

And finally, if (for example) the event’s ‘name’ is always the
category’s name then you can use delegate():

class Event < ActiveRecord::Base
belongs_to :category
delegate :name, :to => ‘(self.category or return “No Category Name”)’
end

<%= event.name %>

Hope this helps,
Trevor

[1] http://www.ccs.neu.edu/home/lieber/LoD.html

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs