builder-7000
builder-7000

Reputation: 7627

Rails helper method return NilClass

I have this code in User#index view:

<%= User.find_each do |user| %>
  <%= user.name %>
<% end %>

which returns the user names:

user1 user2 user3 ...

Then I move this code to the UserHelper:

module UserHelper
  def get_users
    User.find_each do |user|
      user.name
    end
  end
end

And call it from the User#index view with:

<%= get_users %>

The problem is that this is not returning any user. If I use <%= get_users.class %> it outputs NilClass. Why is the helper method not returning the user names?

Upvotes: 1

Views: 118

Answers (2)

ray
ray

Reputation: 5552

You can use as below also,

  <%= User.all.map(&:name).join(' ') %>

Upvotes: 1

Dave Newton
Dave Newton

Reputation: 160251

Your helper method implicitly returns the result of calling find_each, which is different than returning a collection of user names.

Think of it like running 5.times { |n| puts n }: what's the value of that? Not "0 1 2 3 4", but "5", because times returns what it was called on, not what's run in its block.

Your original code, by the way, returns the exact same thing--you are relying on a side effect inside the find_each block, i.e., appending user.name to the response.

If you want to return a collection of the users' names you'd want to map/etc. and grab each user's name. Or, IIRC, you can do a find and a pluck so you only get back the users' names instead of all user fields.

Upvotes: 2

Related Questions