mapping current_user.name as "me" in the options for a select field
How do you include the current_user in the options for select, but map their name to "me"?
A user can assign tasks other users via a select dropdown, but if no other user is selected the task should then be assigned to that user. I'm currently constructing this with a normal select tag with my own helper for the options:
def user_select account
account.users.reject{|u| u == current_user }.map {|user| [user.name, user.id]}
end
and in the form
= f.select :user_id, user_select(@account), { :include_blank => 'me' }
I check to see if the :user_id param is present and set it to the current_user if not. I know, gross, and this is becoming a smell.
So, I'd like to include the current_user in the user_select, but map their user.name as "me." Any ideas?
(I've looked into options_for_select and collections_for_select, and while both allow you to pass in a default, you can't actually set the value. 开发者_如何学GoOr, you can default it to selecting the current_user, but the way I'm doing it currently will use their actual name instead of "me").
Edit: As per fl00r's suggestion, I've changed the user_select to:
def user_select account
me = ["me", current_user.id]
account.users.reject{|u| u == current_user }.map {|user| [user.name, user.id]}.insert(0, me)
end
manually creating the "me" and inserting first works for now.
You need to include "me" only if current_user
belongs to account?
def user_select(account)
me = ["me", current_user.id]
account.users.reject{|u| u == current_user }.map{|user| [user.name, user.id]}.insert(0, me)
end
= f.select :user_id, user_select(@account)
精彩评论