Skip to content

Instantly share code, notes, and snippets.

@alistairtweed
Created April 4, 2017 16:09
Show Gist options
  • Save alistairtweed/92e8f51842c0cd0d6ac9e0f40c851aaf to your computer and use it in GitHub Desktop.
Save alistairtweed/92e8f51842c0cd0d6ac9e0f40c851aaf to your computer and use it in GitHub Desktop.
Ajax Example
= form_for @task, remote: true do |f|
- if @task.errors.any?
.errors
p Please correct the following errors:
ul
- @task.errors.full_messages.each do |message|
li = message
.field
= f.label :name
= f.text_field :name
.actions = f.submit
= form_for task, remote: true do |f|
= f.check_box :is_completed
= f.submit "Update"
= f.label :is_completed, task.name
= link_to "(remove)", task, method: :delete, data: {confirm: "Are you sure?"}, remote: true
<% if @task.errors.any? %>
console.log('An error has occured!');
<% else %>
$('#new_task').remove();
$('#new_link').show();
$('#incomplete_tasks').append('<%= j render(@task) %>');
$('#edit_task_<%= @task.id %>').effect("highlight", {}, 3000).submitOnCheck();
<% end %>
$('#edit_task_<%= @task.id %>').remove();
h1 Check List
= link_to 'New Task', new_task_path, id: "new_link", remote: true
h2 Incomplete Tasks
#incomplete_tasks.tasks
= render @incomplete_tasks
h2 Complete Tasks
#complete_tasks.tasks
= render @complete_tasks
$('#new_link').hide().after('<%= j render("form") %>');
jQuery.fn.submitOnCheck = ->
@find('input[type=submit]').remove()
@find('input[type=checkbox]').click ->
$(this).parent('form').submit()
this
jQuery ->
$('.edit_task').submitOnCheck()
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
def index
sleep 1
@incomplete_tasks = Task.where(is_completed: false)
@complete_tasks = Task.where(is_completed: true)
end
def show
end
def new
@task = Task.new
end
def edit
end
def create
@task = Task.new(permitted_params)
respond_to do |format|
if @task.save
format.html { redirect_to tasks_url, notice: "Task was successfully created." }
format.js
else
format.html do
flash.now[:error] = "Task could not be created."
render :new
end
format.js
end
end
end
def update
respond_to do |format|
if @task.update(permitted_params)
format.html { redirect_to tasks_url, notice: "Task was successfully updated." }
format.js
else
format.html do
flash.now[:error] = "Task could not be updated."
render :edit
end
end
end
end
def destroy
@task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: "Task was successfully destroyed." }
format.js
end
end
private
def permitted_params
params.require(:task).permit(:name, :is_completed)
end
def set_task
@task = Task.find(params[:id])
end
end
<% if @task.is_completed? %>
$('#edit_task_<%= @task.id %>').appendTo('#complete_tasks');
<% else %>
$('#edit_task_<%= @task.id %>').appendTo('#incomplete_tasks');
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment