Rendering a partial from a controller in rails
Edited per the changes in your question. However, nothing really changes. You're thinking about things wrong, and need to adjust how you're thinking. You don't need an alternative show, you need to handle the format.js request.
The partial should be rendered within a JavaScript response, not the controller. The controller looks more like this:
def create @task = Task.new(params[:task]) respond_to do |format| if @task.save format.html { redirect_to @task, notice: 'Task was successfully created.' } format.json { render json: @task, status: :created, location: @task } format.js else format.html { render action: "new" } format.json { render json: @task.errors, status: :unprocessable_entity } format.js end end end
Then, in views/tasks/create.js.coffee
($ '#mytable').append("<%= j render(partial: 'tasks/newly_added', locals: { t: @task }) %>")
What's going on here is that the browser makes a call to create.js
. The controller responds with the create.js
template, because of the respond_to
block's format.js
. The j
escapes the contents of the _newly_added.html.erb
file, and the contents of it are appended to the table. The controller doesn't interact with the existing view, instead, JavaScript is sent to the browser, and it interacts with the view.
This all changes somewhat if you're using a client-side MVC framework like Backbone or Ember, but you didn't specify that so I'm assuming you're going with stock Rails.