JP Richardson
JP Richardson

Reputation: 39385

How can I explicitly declare a view from a Rails controller?

I want to explicitly call a view from my controller.

Right now I have:

def some_action
  .. do something ...
  respond_to do |format|
    format.xml
  end
end

... then it calls my some_action.xml.builder view. How can I call some other view? Is there a parameter in respond_to I'm missing?

Thanks,

JP

Upvotes: 23

Views: 19684

Answers (6)

Nate
Nate

Reputation: 13242

You can modify the internal lookup_context of the controller by doing this in your controller

before_filter do
  lookup_context.prefixes << 'view_prefix'
end

and the controller will try to load view/view_prefix/show.html when responding to an show request after looking for all the other view prefixes in the list. The default list is typically application and the name of the current controller.

class MagicController
  before_filter do
    lookup_context.prefixes << 'secondary'
  end

  def show
    # ...
  end
end

app.get '/magic/1`

This GET request will look for a view in the following order:

  • view/application/show.erb
  • view/magic/show.erb
  • view/secondary/show.erb

and use the first found view.

Upvotes: 2

Fellow Stranger
Fellow Stranger

Reputation: 34013

Or even simpler since Rails > 3.0:

render "edit"

Upvotes: 10

Cameron Price
Cameron Price

Reputation: 1185

You can also pass :action, or :controller if that's more convenient.

respond_to do |format|
    format.html { render :action => 'show' }
end

Upvotes: 5

Kevin Kaske
Kevin Kaske

Reputation: 1139

You could do something like the following using render:

respond_to do |format|
    format.html { render :template => "weblog/show" }
end

Upvotes: 43

Gabe Hollombe
Gabe Hollombe

Reputation: 8067

See the Rendering section of the ActionController::Base documentation for the different ways you can control what to render.

You can tell Rails to render a specific view (template) like this:

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

# Renders the template with a local variable
  render :template => "weblog/show", :locals => {:customer => Customer.new}

Upvotes: 15

Related Questions