LoginSignup
9
9

More than 5 years have passed since last update.

railsのcontrollerごとのviewにclass="active"をつけたいとき

Last updated at Posted at 2016-03-15

動的なclass="active"をcontrollerごとにつけたい、、、、

こんなことってよくあると思います。webサイトではよく見かけることも多いですね。

RailsではApplicationHelperという便利なmoduleがあるので利用していきましょう

application_helper.rb
module ApplicationHelper
  def is_active_controller(controller_name)
    params[:controller] == controller_name ? "active" : nil
  end

  def is_active_action(action_name)
    params[:action] == action_name ? "active" : nil
  end

  def is_active_actions(action_names)
    action_names.include?(params[:action]) ? "active" : nil
  end

  def is_active_controller_and_action(controller_name, action_name)
    if params[:controller] == controller_name && params[:action] ==  action_name
      "active"
    else
      nil
    end
  end
end

このように、たとえば一番はじめの

ruby
 def is_active_action(action_name)
    params[:action] == action_name ? "active" : nil
  end

に対して、たとえばproducts#indexを見ていたとします。
そのとき対応しているcontrollerはproducts_controllerなので

html
  ....
   <li{class: "#{is_active_controller('products')}"}></li>
  ....

というようにすれば、これで

ruby
  resources :products

で生成されるアクション全てに対し、activeを付けることができます。
(とはいってもupdateやdestroyなどはviewが基本的にないので実際はshow,index,newあたりでしょうか)

もしアクションごとにもactiveを付ける、つけないを選択したいのなら2番目の

ruby
 def is_active_action(action_name)
    params[:action] == action_name ? "active" : nil
  end

を使えばよくて、さらに用途を細分化すると

ruby
def is_active_action(action_name)
    params[:action] == action_name ? "active" : nil
end
#一つだけのアクションをactiveにしたい(controllerは関係ない)

def is_active_actions(action_names)
    action_names.include?(params[:action]) ? "active" : nil
end
#複数のアクションをactiveにしたい(controllerは関係ない)

def is_active_controller_and_action(controller_name, action_name)
    if params[:controller] == controller_name && params[:action] ==  action_name
      "active"
    else
      nil
end
#controllerとそのアクションを指定(controllerは関係する)

activeをcss(sass)でカスタマイズすればさらに良い感じになります( ^_^)/~~~

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9