Avoiding nil in Rails Views

I am sure that this has already been asked, but I can not find the answer.

I have a Project model that is relevant belongs_toto my client model. The client has a name, but the project does not necessarily have a client.

In my opinion, I have a code like this:

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

because if the project does not have a client, then an attempt to access it project.client.nameraises a NoMethodError ( nildoes not have a method called name).

The question is, is it acceptable to have this kind of nil check in a view, or should I look for another way around it?

+5
source share
6 answers

Just use

project.client.try(:name)
+10
source

, - , , , .

+3

, , . , , , , .

- . Project client_name, , , , .

def client_name
  client && client.name
end

, .:)

Skilldrick , :

def client_name
  client ? client.name : "no client"
end
+3

delegate Project, demeter, , " ".

project.rb

class Project
  delegate :name, to: :client, prefix: true, allow_nil: true    
end

, , :

#You can now call
project.client_name

delegate Rails.

+2

. , - - . , , - .

application_helper.rb:

  def none_on_fail
      begin
          return yield
      rescue
          return "(none entered)"
      end
  end

:

<%= none_on_fail { project.client.name }  %>

, , , //, . . .

0

, . , , , . .

, , . , show, . , , html, - . , @array.each do |a| end, , . , , . @page_title || #{@APP_CONFIG['page_title']} (. Railscasts # 85). , , , .

These are a few scenarios where presence and use checks can be avoided try. I will try to avoid them if possible. If you cannot avoid them, I would put conditional checks in the view helper and add an auxiliary unit test to check (and document) both code paths.

0
source

All Articles