0

I'm trying to display the school name for the users. When they sign up users can select a school which they belong to (not everyone does though so sometimes this column is left blank).

At the moment I have:

if user.is_a? Student
  %td= user.school
end

which finds the schools that the students belong to, but displays it as the activerecord record. Each of the schools has a name and if I select a single student and do: @student.school.name it gives me the name of the school with no issues.

However if I do:

if user.is_a? Student
  %td= user.school.name
end

It keeps throwing up undefined methodname' for nil:NilClass`

I am pretty sure this is because some of the students don't have a school. I have tried to add this to the if statement but I can't seem to make it work. I tried variations of:

if user.is_a? Student && !user.school.blank?

with .any?, .empty? but none of them work, they just so no method .blank? etc.

Any help please?

camillavk
  • 521
  • 5
  • 20

3 Answers3

2

I would do one of these things

A) quickest

 %td= user.school && user.school.name

B) cleanest (or, at least, cleaner)

#in user class
def school_name
  self.school && self.school.name
end

#in view
%td= user.school_name
Max Williams
  • 32,435
  • 31
  • 130
  • 197
0

you can use try (http://apidock.com/rails/Object/try) method here

if user.is_a? Student
  %td= user.school.try(:name)
end
ramkumar
  • 628
  • 8
  • 15
0

You can use one-liner with present? method for showing one value when no school present and school name when it is present:

%td= user.school.present? ? user.school.name : '-'

Here is a nice table that explains differences between methods like nil?, empty?, present? etc.

NB! It's not good practice to write logic into view-files so I suggest putting it inside helper method:

inside view:

%td= school_name(user)

inside user_helper.rb:

def school_name(user)
  user.school.present? ? user.school.name : '-'
end
Community
  • 1
  • 1
Andres
  • 2,099
  • 3
  • 22
  • 39