Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Todo List AJAX the Rails Way demo
<h1>My Todos</h1>
<%= form_for Todo.new, remote: true do |f| %>
<div class="form-group">
<%= f.text_field :description, placeholder: "What needs doing?" %>
</div>
<div class="form-group">
<%= f.text_field :priority, placeholder: "Priority Level" %>
</div>
<div class="form-group">
<%= f.submit %>
</div>
<% end %>
<li id="todo_<%= todo.id %>">
<%= link_to(todo.description, todo_path(todo)) %><br>
Priority: <%= todo.priority %>
<%= link_to "Done", todo_path(todo), method: :delete, remote: true %>
</li>
// Escapes carriage returns and single and double quotes for JavaScript segments.
$('ul').append("<%= j render partial: 'todo', locals: {todo: @todo} %>")
$('form')[0].reset();
$('li#todo_<%= @todo.id %>').slideUp();
<%= render 'todos/new' %>
<ul>
<%= render @todos %>
</ul>
<h1><%= @todo.description %></h1>
<h3><%= @todo.priority %></h3>
class TodosController < ApplicationController
def index
@todos = Todo.all
respond_to do |f|
f.html
f.json { render json: @todos }
end
end
def show
@todo = Todo.find(params[:id])
respond_to do |f|
f.html
f.json { render json: @todo }
end
end
def create
@todo = Todo.create(todo_params)
respond_to do |f|
# if the response fomat is html, redirect as usual
f.html { redirect_to root_path }
# if the response format is javascript, do something else...
f.js {}
end
end
def destroy
@todo = Todo.find(params[:id])
@todo.destroy
respond_to do |f|
f.html { redirect_to root_path }
f.js {}
end
end
private
def todo_params
params.require(:todo).permit(:description, :priority)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment