DEV Community

Discussion on: Rails Layouts

Collapse
 
andrewbrown profile image
Andrew Brown 🇨🇦

If you want to set a controller to utilize a specific layout for all its actions
Notice its

layout 'admin'
Enter fullscreen mode Exit fullscreen mode

instead of

layout :admin
Enter fullscreen mode Exit fullscreen mode

since passing a symbol does something different.

class UsersController < ApplicationController
  layout 'admin'
end
```



So lets say you wanted to only apply layout to specific actions maybe you think you could do this because you can do this with before_actions:



````rb
class UsersController < ApplicationController
  layout 'form', only: %w{new create edit update}
end
```
{% endraw %}


This, however, doesn't work, so how do you get conditional layouts? This is where symbol comes in, its actually telling it to call a function in the controller to handle the logic
{% raw %}


````rb
class UsersController < ApplicationController
  layout :guess


  def guess
    case action_name
    when "new", "create", "edit", "update"
      "form"
    else
      "application"
    end
  end

end
```



Also you noticed when I did this:


```
%w{new create edit update}
```



This is a clever shorthand for arrays which will split on the space so its the same as:



```rb
['new', 'create' , 'edit' , 'update']
```



I keep thinking about making an open-source Rails course, can you tell?
Enter fullscreen mode Exit fullscreen mode