Aasish Sharma Aasish Sharma - 4 months ago 16
MySQL Question

Show current user as "Me" in select tag

I have used the below-written code to select the users

def user_for_select
User.pluck(:name, :id).unshift(['All', 'all'])
end


But I want to display the current user's name as "Me" in the select tag.

Answer

You can do like:

def user_for_select
  User
    .pluck("CASE WHEN id = #{current_user.id} THEN 'ME' ELSE name END AS name, id")
    .unshift(['All', 'all'])
end

Tested in my own rails console (Rails 4.2.6):

Admin.pluck("CASE WHEN id = #{u.id} THEN 'ME' ELSE full_name END AS name, id").unshift(['All', 'all'])
# (0.6ms)  SELECT CASE WHEN id = 7 THEN 'ME' ELSE full_name END AS name, id FROM "admins"
# => [["All", "all"], ["arup rakshit", 1], ["ME", 7], ["pinaki das", 2], ["mina das", 3], ["proloy das", 4], ["mouli roy", 5], ["pisi das", 6]]

EDIT: If the method is class method like below.

class User < AR
  class << self
    def user_for_select(user)
      self
        .pluck("CASE WHEN id = #{user.id} THEN 'ME' ELSE name END AS name, id")
        .unshift(['All', 'all'])
    end
  end
end

Now from view call it like :

user_for_select(current_user)