rails “undefined method” when invoking a helper method from the view

1k Views Asked by At

I want to get the gender of a person from a helper method like so:

sportists_helper.rb

def sportists_gender
  gender = self.gender

  if gender == "1"
    "Male"
  elsif gender == "2"
    "Female"
  end
end

and then print it out in a view: <%= sportists_gender %>, but this gives me undefined method 'gender' error, why is that?

1

There are 1 best solutions below

2
On BEST ANSWER

Assuming you have Person model. here is an example:

Helper:

def sportists_gender(person)
  gender = person.gender

  if gender == "1"
    "Male"
  elsif gender == "2"
    "Female"
  end
end

Call From View.erb:

 <% @person = Person.first %> // any object according to your view.
 <%= sportists_gender(@person) %> // display result.