cjm2671
cjm2671

Reputation: 19486

How do I access helpers I've written in Rails?

I've written a helper for my user model in user_helper.rb

module UserHelper
  def get_array_of_names_and_user_ids
    User.all(&:first_name) + User.all.map(&:user_id)
  end
end

Unfortunately when I type in

 <div class="field">
        <%= f.label :assignee, "Assigned to" %>
        <%= select(:task, :assignee_id, User.get_array_of_names_and_user_ids )%>
  </div>

It can't see it. Where am I going wrong? I'm using devise.

Upvotes: 2

Views: 49

Answers (4)

Harish Shetty
Harish Shetty

Reputation: 64363

You don't need to hand code this helper as Rails provides a helper called collection_select for this purpose.

In your view simply add this:

<%= collection_select(:task, :assignee_id, User.all, :id, :first_name, 
   :prompt => true) %>

Note:

I am assuming you have a small set of users in your DB(<30). Otherwise, you have to use some other control to select users.

Upvotes: 1

antonversal
antonversal

Reputation: 1239

Helpers are for views not for model. For model you should define class methods in User model

class User
  def self.get_array_of_names_and_user_ids
    User.all(&:first_name) + User.all.map(&:user_id)
  end
end

Upvotes: 2

chrispanda
chrispanda

Reputation: 3224

Helpers are methods that can be called in the view, not methods to be called on the model Just call get_array_of_names_and_user_ids

Upvotes: 0

Kelly
Kelly

Reputation: 41571

You're close. The helper doesn't become a class method like that -- it becomes accessible as a method in your views. Just simply call get_array_of_names_and_user_ids.

Upvotes: 4

Related Questions