If action_name Rails

I use if action_name to define the layout e.g.

layout :layout_by_action_name

def layout_by_action_name
  if action_name == 'new'
    "layout_file"
  else
    "application"
  end
end

How to add another action name with new, for example edit. I tried:

layout :layout_by_action_name

def layout_by_action_name
  if action_name == 'new' && 'edit'
    "layout_file"
  else
    "application"
  end
end

But it does not work. Any ideas?

+7
source share
4 answers

Try:

if action_name == "new" or action_name == "edit"

Or:

if ["new", "edit"].include? action_name
+12
source

You probably want:

if action_name == 'new' || action_name == 'edit'
+3
source

, MrDanA, , :

if ["new", "edit"].include?(action_name)
+1

Rails 3. 1+ in?, :

layout :layout_by_action_name

def layout_by_action_name
  if action_name.in?('new','edit')
    'layout_file'
  else
    'application'
  end
end

Rails 4+ , :

layout ->{ action_name.in?('new','edit') ? 'layout_file' : 'application' }

, , :

def layout_by_action_name
  case action_name
  when 'new','edit'
    'layout_file'
  when 'delete'
    'other_file'
  else
    'application'
  end
end

, , , render:

def new
  ...
  render layout: 'layout_file'
end

def edit
  ...
  render layout: 'layout_file'
end

This last option may even be the best option if you redefine the layout for only a small number of actions, because it is very clear.

0
source

All Articles