rohan rohan - 7 months ago 16
Ruby Question

Specifying layout in namespaced controller

I am creating a new version of one of my controllers,

Original Controller:-

class ExampleController < ApplicationController
layout 'filename', only: [:method_name]
...
def method_name
#...some logic...
respond_to do |format|
format.html
format.json {
render json: {}, root: false
}
end
end
...
end


New Controller:-

class V1::ExampleController < ApplicationController
layout 'filename', only: [:method_name]
...
def method_name
#...some logic...
respond_to do |format|
format.html
format.json {
render json: {}, root: false
}
end
end
...
end


I keep getting error:-

Missing template v1/example/filename, application/filename with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :arb, :haml, :jbuilder]}


One of the solution is to create a folder structure v1/example and put my layout file there too. But I do not want to create duplicate copies of this file.

Another is to use a parent controller class of both new and old example_controller and specify layout there(and have a folder structure according to the name of the parent class). But this will be an overkill and also I plan on deleting old controller once all my clients migrate to new versions.

I also tried specifying like this:-

class V1::ExampleController < ApplicationController
layout 'example/filename', only: [:method_name]
...
end


but this also doesn't work.

How to tell my new controller to render layout from the old folder structure.

Answer
format.html {
  render template: 'path/to/template'
}

Rendering a template

Template rendering works just like action rendering except that it takes a path relative to the template root. The current layout is automatically applied.

# Renders the template located in [TEMPLATE_ROOT]/weblog/show.r(html|xml) (in Rails, app/views/weblog/show.erb)
render :template => "weblog/show"`

See reference for #render

Comments