Brian McDonough
Brian McDonough

Reputation: 14499

Check to see if a field is blank in rails

I've looked at these posts on stack overflow: A concise explanation of nil v. empty v. blank in Ruby on Rails Rails: How do I check if a column has a value?

And I've tried out some different ways to check a record's existence, but my code is still throwing an error:

undefined method `links' for nil:NilClass

I have this is application_controller:

def header_links_when_signedin
  if signed_in? 
    @header = @current_group.navbars.where(:header => true, :signedin => true).first
    unless @header.links.first.blank?
      @header.links
    end
  end
end

And I get the error on this line:

unless @header.links.first.blank?

Or anywhere I include links when I have not previously created a link for the navbar I am calling.

Everything works fine when I have created the fields, I'm just covering the use case for when a link for a navbar has not been created yet for a group.

Upvotes: 1

Views: 1295

Answers (2)

cpuguy83
cpuguy83

Reputation: 5993

Even better:

@header.try(:links)

This will automatically check if @header is nil before calling "links" on it.

And if you really care you can do:

@header.try(:links) unless @header.try(:links).try(:empty?)

But you should figure out why @header is nil.

Upvotes: 1

cortex
cortex

Reputation: 5206

The problem is that @header is nil (no header was found). To avoid the error try:

if @header && @header.links
  @header.links
end

Here you verify that @header and @header.links "exist". Btw, what do you want to do with your instance variable @header? Because @header.links is not doing anything.

Upvotes: 3

Related Questions