清除在Rails中突出显示活动按钮的通用方法

时间:2016-07-27 19:28:01

标签: ruby-on-rails

我试图突出显示三个按钮中的一个。我对目前这样做的方式不太满意,所以我想问你一些问题。

我有三个按钮应该对我使用的过滤器有效:我的门票,团队门票和特定用户的门票。

# tickets_controller.rb

@filter_by_user_id_active = Array.new
ba = %w(btn-default btn-primary)

# Determine, which button to highlight
if @user == current_user
  @filter_by_user_id_active[0] = ba[1]
  @filter_by_user_id_active[1] = ba[0]
  @filter_by_user_id_active[2] = ba[0]
elsif @user != nil && @user != current_user
  @filter_by_user_id_active[0] = ba[0]
  @filter_by_user_id_active[1] = ba[0]
  @filter_by_user_id_active[2] = ba[1]
else
  @filter_by_user_id_active[0] = ba[0]
  @filter_by_user_id_active[1] = ba[1]
  @filter_by_user_id_active[2] = ba[0]
end 

在视图中:

= link_to "?user_id=#{current_user.id}", {:type => "button",
:class => "btn #{@filter_by_user_id_active[0]}"} do
My tickets

其他链接使用[1][2]

这是其中一个链接。控制器根据条件返回btn-defaultbtn-primary。但我发现,这不是干净和通用的代码。

你有什么想法吗?

提前致谢!

3 个答案:

答案 0 :(得分:1)

一种更简单的方法就像这个

ba = %w(btn-default btn-primary)    
@filter_by_user_id_active = [ba[0],ba[0],ba[0]]


if @user == current_user
  @filter_by_user_id_active[0] = ba[1]
elsif @user.present?
  @filter_by_user_id_active[2] = ba[1]
else
  @filter_by_user_id_active[1] = ba[1]
end

但是,如果我必须这样做,那么我不会在控制器或独立逻辑中添加此类决策。相反,我会做一些像:

= link_to "?user_id=#{current_user.id}", {:type => "button",
:class => "btn #{@user==current_user ? "btn-primary" : 'btn-default'}"} do
My tickets
end

类似地,对于其他两个链接,相同的逻辑只是条件更改,如@user != current_user@user.blank?

<强>更新

您可以为整个按钮定义辅助方法,例如

def link_to_tickets url , text,active_class_condition
    link_to url, {:type => "button",:class => "btn #{active_class_condition ? "btn-primary" : 'btn-default'}"} do
        text
    end
end

然后在您的视图中调用此方法

=link_to_tickets "?user_id=#{current_user.id}" , "My Tickets" , @user == current_user

答案 1 :(得分:1)

我建议避免在控制器中使用那种逻辑。在您看来,另一种可能的解决方案是:

= link_to "?user_id=#{current_user.id}", {:type => "button", :class => "btn #{link_class(0)}"} do

并在您的(无论如何)_helper.rb 中,您可以这样做:

def link_class(index)
  return 'btn-primary' if @user == current_user && index == 0
  return 'btn-primary' if @user && @user != current_user && index == 2
  return 'btn-primary' if index == 1
  'btn-default' 
end

根据您的意愿使用 index 。其余的链接也会这样做,只需传递正确的索引。您还可以使用将所有 返回放在一行中,但这看起来不像示例中那样可读

更新:该功能的简化版本为:

def link_class(index)
  return 'btn-primary' if @user && [0,2].include?(index) || index == 1
  'btn-default' 
end

[0,2] .include?(index)是因为那两个需要 @user index == 1 不需要它。

答案 2 :(得分:0)

一种解决方案可能是这样的:

ba = %w(btn-default btn-primary)
@filter_by_user_id_active = Array.new(3){ba[0]}
  

无需每次都更新所有按钮

if @user == current_user
  @filter_by_user_id_active[0] = ba[1]
elsif @user.present?
  @filter_by_user_id_active[2] = ba[1]
else
  @filter_by_user_id_active[1] = ba[1]
end