简体   繁体   中英

After an AJAX action to create, how do you send back an updated collection of objects in Rails?

So I am confused about how to send back an updated collection of @tasks after the create action so that I can see the newly created item on the page without having to do a refresh. How do I do this? Let me walk you through my code in order.

First, here is my index.html.erb code:

<div class="row">
  <div class="col-md-5 col-md-offset-1">
    <h2>Tasks</h2>
  </div>

  <div class="col-md-2 col-md-offset-4">
    <%= link_to new_task_path, remote: true do %>
      <button class="btn btn-default">New</button>
    <% end %>
  </div>
</div>

<div class="row">
  <div class="col-md-6 col-md-offset-2" id="task-form" style="display:none;"></div>
</div>

<div class="row">
  <div class="col-md-7 col-md-offset-1" id="tasks"><%= render @tasks %></div>
</div>

I will click on the "New" button which hits the new action of the controller. Here is my controller code:

class TasksController < ApplicationController
  before_action :all_tasks, only: [:create, :update]
  before_action :set_tasks, only: [:edit, :update]

  respond_to :html, :js

  # index action has been removed
  def index
    @tasks = Task.all

    respond_to do |format|
      format.html
      format.json
    end
  end

  def new
    @task = Task.new
  end

  def create
    @task  = Task.create(task_params)
  end

  def update
    @task.update_attributes(task_params)
  end

  private

  def all_tasks
    @tasks = Task.all
  end

  def set_tasks
    @task = Task.find(params[:id])
  end

  def task_params
    params.require(:task).permit(:description, :deadline)
  end
end

This will render the new.js.erb code:

$('#task-form').html("<%= j (render 'form') %>");
$('#task-form').slideDown(350);

This will render the new form:

<%= simple_form_for @task, remote: true do |f| %>
  <%= f.input :description %>
  <%= f.input :deadline %>
  <%= f.button :submit %>
<% end %>

When I hit submit, it will hit the create action of the controller again

def create
    @task  = Task.create(task_params)
  end

After here, what I would like to do is send back an updated collection of @tasks and render them on the page. Is there anyway I can just render the index.html.erb view again and send it Task.all?

Add instance variable @tasks in your def create

def create
  @task  = Task.create(task_params)
  @tasks = Task.all
  respond_to do |format|
    format.js
  end
end

Create a new file create.js.erb

$('#tasks').html("<%= j (render @tasks) %>");

在您的情况下,您的create.js.erb将如下所示:

$('#tasks').append("<li> <%= @task.inspect %> </li>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM