在选择标记中显示当前用户的数据及其名称

时间:2016-08-17 04:50:04

标签: mysql ruby-on-rails

我希望根据通过导航栏传递的参数值显示当前用户的(经理)数据,并在select标签中显示其名称,用户有两个角色('用户','经理')或枚举角色(0,1)。 这是我在导航栏中给出的链接 -

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

但是在控制器中它变得越来越复杂,因为我使用的查询就是这些 -

    @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

最后我使用的选择标签 -

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();")

用户模型 -

      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

2 个答案:

答案 0 :(得分:0)

我不知道你为什么需要在选择列表中加载current_user。但您可以在用户模型中自定义选择,如下所示:

def user_for_select(user)
  self
    .where(id: user.id)
    .pluck("CASE WHEN id = #{user.id} THEN 'Me' ELSE name END AS name, id")
  end
end

编辑取决于评论:

在用户模型中添加以下方法:

def is_manager?
   self.role == "manager"
end

然后按以下步骤更新选择:

def user_for_select(user)
  if user.is_manager?
      self
        .pluck("CASE WHEN id = #{user.id} THEN 'Me' ELSE name END AS name, id")
        .unshift(['All', 'all'])
  else
       self
         .where(id: user.id)
         .pluck("CASE WHEN id = #{user.id} THEN 'Me' ELSE name END AS name, id")
  end
end

答案 1 :(得分:0)

这就是我得到结果的方法,在导航栏中做了这个改变 -

- if is_manager?
  %li= link_to 'Timesheet', timesheet_path(u_id: current_user.id) 
- else
  %li= link_to 'Timesheet', timesheet_path

并在select标签中进行此更改 -

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();")