Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding nil in Rails views

I'm sure this has been asked already, but I can't find the answer.

I have a Project model, which has a belongs_to relationship with my Client model. A client has a name, but a project doesn't necessarily have a client.

In my view, I've got code like this:

<%=h project.client && project.client.name %>

because if the project doesn't have a client then trying to access project.client.name causes a NoMethodError (nil doesn't have a method called name).

The question is, is it acceptable to have this kind of nil checking in the view, or should I be looking for another way around it?

like image 579
Skilldrick Avatar asked Aug 21 '10 12:08

Skilldrick


2 Answers

Just use

project.client.try(:name)
like image 98
Reactormonk Avatar answered Nov 03 '22 11:11

Reactormonk


I think its perfectly acceptable - this is view logic, you are more or less deciding whether or not to show portions of your view, based on whether there is data.

like image 3
jasonpgignac Avatar answered Nov 03 '22 11:11

jasonpgignac