1

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.

Community
  • 1
  • 1
Brian McDonough
  • 13,829
  • 4
  • 19
  • 23

2 Answers2

3

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.

cortex
  • 5,036
  • 3
  • 31
  • 41
1

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.

cpuguy83
  • 5,794
  • 4
  • 18
  • 24
  • 1
    While I agree I wouldn't chain tries like that, I think using try is much cleaner than explicitly checking for nil, and you end up with the same result either way. Also do note the linked article is dealing with hashes, which has better ways than using try, the second article on it is more about Demeter issues. – cpuguy83 Jul 02 '13 at 00:18