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.
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
.
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
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.
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
精彩评论