How to handle nils in views?

I have the following models installed:

class Contact < ActiveRecord::Base belongs_to :band belongs_to :mode validates_presence_of :call, :mode validates_associated :mode, :band validates_presence_of :band, :if => :no_freq? validates_presence_of :freq, :if => :no_band? protected def no_freq? freq.nil? end def no_band? band.nil? end end class Band < ActiveRecord::Base has_many :logs end class Mode < ActiveRecord::Base has_many :logs end 

When I enter a frequency in my new view, it does not allow me to specify a range if a frequency is entered. This creates a problem in my other views, because the group is now zero. How to allow the group not to be indicated and just display as empty in my index and display the views, and then in the edit window to allow it to be indicated at a later point in time.

I was able to get my index to display a space by doing:

 contact.band && contact.band.name 

But I'm not sure if this is the best approach, and I'm not sure how to apply a similar solution to my other views.

Thanks a lot for newb rails!

+4
source share
5 answers

In my views, I use the following for potentially null objects in my views:

 <%= @contact.band.name unless @contact.band.blank? %> 

if your object is an array or hash, can you use empty? instead of this.

 <%= unless @contacts.empty? %> ..some code <% end %> 

Hope this helps!

D

+8
source
 <%= @contact.try(:band).try(:name) %> 

This will return nil if band or name does not exist as methods for its corresponding objects.

+2
source

You can use Object # and for this:

 <%= @contact.band.andand.name %> 
+1
source

A couple of years, but still a great Google result for "rails view handle nil", so Iโ€™ll add my suggestion for use with Rails 3.2.3 and Ruby 1.9.3p0.

In application_helper.rb add the following:

 def blank_to_nbsp(value) value.blank? ? "&nbsp;".html_safe : value end 

Then, to display the value in the view, write something like this:

 <%= blank_to_nbsp contact.band %> 

Benefits:

  • "blank" catches both nil values โ€‹โ€‹and empty strings ( details ).
  • Simply deleting a null object or using an empty string can lead to formatting problems. &nbsp; pushes unused space onto a web page and retains formatting.
  • With the sentences โ€œifโ€ and โ€œifโ€ in the other answers, you must enter each object name twice. Using the helper, you only need to enter the name of each object once.
+1
source

<%= @contact.band if @contact.band %> also works

0
source

Source: https://habr.com/ru/post/1306368/


All Articles