sharma_a sharma_a - 3 months ago 10
MySQL Question

Show current User's data and it's name in select tag

I want to display the current user's (manager) data based on params value passed through navbar and it's name in select tag, User has two role ('user', 'manager') or enum role (0 , 1).
This is the link I have given in navbar -

%li= link_to 'Timesheet', is_manager? ? timesheet_path(user_id: current_user.id) : timesheet_path, class: navlink_class('timesheets')


But in the controller it is getting complicated as the queries which I have used are these -

@begin_date = params[:begin_date].present? ? Date.parse(params[:begin_date]) : Date.today.beginning_of_month
@end_date = params[:end_date].present? ? Date.parse(params[:end_date]) : Date.today.end_of_month
begin_datetime = @begin_date.beginning_of_day
end_datetime = @end_date.end_of_day
@user_tasks = Task.joins(:task_time_trackers).where("(task_time_trackers.created_at BETWEEN ? AND ?)",begin_datetime, end_datetime ).distinct.order("id ASC")
user_trackers = TaskTimeTracker.joins(:task).where("(task_time_trackers.created_at BETWEEN ? AND ?)",begin_datetime, end_datetime )
u_id = nil
u_id = params[:u_id] if (params[:u_id] && params[:u_id] != 'all')
u_id = current_user.id if current_user.role == 'user'
unless u_id.nil?
@user_tasks = @user_tasks.where( task_time_trackers: { user_id: u_id})
user_trackers = user_trackers.where( task_time_trackers: { user_id: u_id})
end


And finally the select tag which I have used -

select_tag(:u_id, options_for_select(User.user_for_select(current_user), selected: params[:u_id]), class: "input-sm form-control", onchange: "this.form.submit();")


User Model -

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

Answer

This is how I got the result, in the navbar made this change -

%li= link_to 'Timesheet', timesheet_path(u_id: current_user.id), class: navlink_class('timesheets')

and in the select tag this change -

select_tag(:u_id, options_for_select(User.user_for_select(current_user), params[:u_id]), class: "input-sm form-control", onchange: "this.form.submit();")