Full Calendar changes not persisting: event drag and event resize - ruby-on-rails

I have installed full calendar into my ruby on rails app. I cannot figure out why changes are not persisting. I want to use the drag/drop and resize features. I have followed their documents but I'm stuck.
I think i've made an error on callback url?
I appreciate the help!
Fullcalendar docs:
https://fullcalendar.io/docs/eventResize
appointment_calendar.js:
$(document).ready(function() {
var arr = $('#business_appointment').data('url');
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today myCustomButton',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek',
},
defaultView: 'agendaWeek',
editable: true,
selectable: true,
nowIndicator: true,
timezone: "Australia/Brisbane",
events: arr,
//header and other values
select: function(start, end, allDay) {
starttime = moment(start).format("ddd, MMM Do YYYY, h:mm a");
endtime = moment(end).format("ddd, MMM Do YYYY, h:mm a");
todaytime = moment().format("ddd, MMM Do YYYY, h:mm a");
var mywhen = starttime + ' - ' + endtime;
$('#createEventModal #appointment_from').val(starttime);
$('#createEventModal #appointment_to').val(endtime);
$('#createEventModal #apptAllDay').val(allDay);
$('#createEventModal #when').text(mywhen);
$('#createEventModal').modal('show');
},
eventDrop: function(event, delta, revertFunc) {
event_data = {
event: {
id: event.id,
start: event.start.format(),
end: event.end.format()
}
};
$.ajax({
url: "/app/calendar/" + calEvent.id + "/edit",
data: event_data,
type: 'PATCH'
});
},
eventResize: function(event, delta, revertFunc) {
alert(event.title + " end is now " + event.end.format());
if (!confirm("is this okay?")) {
revertFunc();
}
},
eventClick: function(calEvent, jsEvent, view) {
$.ajax({
type: 'GET',
url: "/app/calendar/" + calEvent.id + "/edit",
dataType: "script"
});
},
eventRender: function(event, element)
{
element.find('.fc-time').append("<br/>" + event.residentname);
element.find('.fc-time').append("<br/>" + event.appointmenttype);
}
});
$('#submitButton').on('click', function(e){
// We don't want this to act as a link so cancel the link action
e.preventDefault();
doSubmit();
});
function doSubmit(){
$("#createEventModal").modal('hide');
console.log($('#apptStartTime').val());
console.log($('#apptEndTime').val());
console.log($('#apptAllDay').val());
$("#calendar").fullCalendar('renderEvent',
{
title: $('#residentName').val(),
start: new Date($('#apptStartTime').val()),
end: new Date($('#apptEndTime').val()),
allDay: ($('#apptAllDay').val() == "true"),
},
true);
}
});
calendar_controller.rb:
require "datetime_format"
class App::CalendarController < App::BaseController
include DateTimeFormat
before_action :set_appointment, only: [:edit,:update]
def index
#arr = []
#business_appointments = current_business.appointments
#business_appointments.each do |business_appointment|
hash = {}
hash["start"] = business_appointment.start
hash["end"] = business_appointment.end
hash["title"] = business_appointment.name
hash["residentname"] = "#{business_appointment.resident.first_name} #{business_appointment.resident.last_name}"
hash["appointmenttype"] = business_appointment.appointment_type.name
hash["id"] = business_appointment.id
#arr << hash
end
#global_arr = #arr
#appointment = current_business.appointments.new
end
# POST/calender_appointment
def create
#appointment = current_business.appointments.new(appointment_params)
#appointment.author_id = current_user.id
respond_to do |format|
if #appointment.save!
format.html { redirect_to app_calendar_index_path, notice: 'Appointment was successfully created.' }
format.json { render :index, status: :created, location: #appointment }
else
format.html { redirect_to app_calendar_index_path, notice: 'Unable to create appointment.' }
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
def edit
end
# PATCH/PUT /update_calender_appointment
def update
#appointment.author_id = current_user.id
respond_to do |format|
if #appointment.update(appointment_params)
format.html { redirect_to app_calendar_index_path, notice: 'Appointment was successfully updated.' }
format.json { render :show, status: :ok, location: #appointment }
else
format.html { redirect_to app_calendar_index_path, notice: 'Unable to update appointment.' }
format.json { render json: #appointment.errors, status: :unprocessable_entity }
end
end
end
private
def set_appointment
#appointment = current_business.appointments.find(params[:id])
end
def appointment_params
if params[:action].eql?("create")
params[:appointment][:start] = format_datetime(params[:start]).to_datetime
params[:appointment][:end] = format_datetime(params[:end]).to_datetime
end
params.require(:appointment).permit(:name, :description, :start, :end, :resident_id, :appointment_type_id)
end
end

It was my error, needed to add this code:
updateAppointment = (event) => {
let event_data = {
appointment: {
id: event.id,
start: event.start.format(),
end: event.end.format()
}
};
$.ajax({
url: "/app/calendar/" + event.id,
data: event_data,
type: 'PUT'
});
}

Related

Unable to update Stripe accounts with URI error

I receive the following error when attempting to update Stripe Connect accounts:
bad URI(is not URI?): /v1/accounts/{ "id": "acct_xxxxxxxxxxxxxxxxxx", "object": "account", "business_profile": { "mcc": null, "name": null, "product_description":
....
....
I am able to create accounts but updating them doesn't seem to work. I am using the same form and similar code in the controller. This is my update method in controller:
def update
unless (current_user || current_affiliate).stripe_account
redirect_to new_user_stripe_account_path and return
end
begin
#stripe_account_retrieve = Stripe::Account.retrieve((current_user || current_affiliate).stripe_account.acct_id)
stripe_account_params.each do |key, value|
if value.empty?
flash.now[:alert] = "Please complete all fields."
render 'edit' and return
end
end
if #stripe_account.account_type == "individual"
Stripe::Account.update(
#stripe_account_retrieve,
{
:country => stripe_account_params[:country],
:type => "custom",
:business_type => stripe_account_params[:account_type],
requested_capabilities: ['platform_payments'],
individual: {
address: stripe_account_params[:address_line1],
first_name: stripe_account_params[:first_name],
last_name: stripe_account_params[:last_name],
ssn_last_4: stripe_account_params[:ssn_last_4],
# phone: stripe_account_params[:business_tax_id],
dob: {
day: stripe_account_params[:dob_day],
month: stripe_account_params[:dob_month],
year: stripe_account_params[:dob_year]
},
address: {
line1: stripe_account_params[:address_line1],
city: stripe_account_params[:address_city],
state: stripe_account_params[:address_state],
postal_code: stripe_account_params[:address_postal]
},
},
tos_acceptance: {
date: Time.now.to_i,
ip: request.remote_ip
}
})
....
....
respond_to do |format|
#stripe_account = StripeAccount.find(params[:id])
if #stripe_account.update(stripe_account_params)
format.html { redirect_to #stripe_account, notice: 'Stripe account was successfully updated.' }
format.json { render :show, status: :ok, location: #stripe_account }
else
format.html { render :edit }
format.json { render json: #stripe_account.errors, status: :unprocessable_entity }
end
end
end
end
According to the docs, I don't see anything I am doing wrong...
https://stripe.com/docs/api/accounts/update
My edit in controller:
def edit
#stripe_account_retrieve = Stripe::Account.retrieve((current_user || current_affiliate).stripe_account.acct_id)
#stripe_account = StripeAccount.find(params[:id])
end
When i submit the update form (this is ahead of the error:)
Started PATCH "/stripe_accounts/27" for 127.0.0.1 at 2019-04-03 20:16:38 -0400
Processing by StripeAccountsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"3//b+Exxxf9xxxtagFbsdzMxxxW+wxxxx899FDLfMb/RxxxxQA==", "stripe_account"=>{"first_name"=>"seller21114", "last_name"=>"last2124", "ssn_last_4"=>"2222", "dob_month"=>"1", "dob_day"=>"10", "dob_year"=>"1912", "address_line1"=>"111 st", "address_city"=>"san fran", "country"=>"US", "address_state"=>"IL", "address_postal"=>"90210", "tos"=>"1"}, "2"=>"", "button"=>"", "id"=>"27"}
IS there anything I am doing wrong here with my code?
Stripe::Account.update(
#stripe_account_retrieve,... )
this should be
Stripe::Account.update(
#stripe_account_retrieve[:id], ...)
i.e., pass the ID of the Account object you retrieved, not the full object itself.
Or just pass the value of (current_user || current_affiliate).stripe_account.acct_id directly to Stripe::Account.update, since you don't seem to currently use the retrieved account for anything else so you may as well save youself a GET request :)

Build array from two hashes

I try to build json with geojson datas.
In my controller :
def index
....
respond_to do |format|
format.html
format.json { render json: { type: 'FeatureCollection', features: pois_geojson + tracks_geojson} }
end
and for show
def show
...
respond_to do |format|
format.html
format.json { render json: { type: 'FeatureCollection', features: poi_geojson + track_geojson} }
end
For index, all work fine and my json is good. I call this method for build json.
Methods for show
def poi_geojson
{
type: 'Feature',
RGeo::GeoJSON.encode(#poi.lonlat),
properties: {
name: #poi.name,
:'marker-color' => '#00607d',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
}
}
end
def track_geojson
{
type: 'Feature',
geometry: RGeo::GeoJSON.encode(#track.path),
properties: {
:'color' => '#ff7800',
:'weight' => '5',
:'opacity' => '0.65'
}
}
end
Methods for index
def pois_geojson
#pois.map do |poi|
{
type: 'Feature',
RGeo::GeoJSON.encode(poi.lonlat)
properties: {
name: poi.name,
:'marker-color' => '#00607d',
:'marker-symbol' => 'circle',
:'marker-size' => 'medium'
}
}
end
end
def tracks_geojson
#tracks.map do |track|
{
type: 'Feature',
geometry: RGeo::GeoJSON.encode(track.path),
properties: {
:'color' => '#ff7800',
:'weight' => '5',
:'opacity' => '0.65'
}
}
end
end
As you can see, the methods are similars, but I don't understand why for index it work fine, and not for the show.
I have this error :
`undefined method '+' for #`
for this line :
`format.json { render json: { type: 'FeatureCollection', features: poi_geojson + track_geojson} }`
There is no + method for hash instances, to form an array from two hashes you can do the following:
[pois_geojson, tracks_geojson]
The reason why this works for pois_geojson and tracks_geojson is because both of them are already arrays.

dropzone.js not redirecting or rendering errors properly on failure

Everything is working fine with dropzone.js except when a photo fails to upload.
if the form is submitted with a photo attached that is too big or the form is submitted without a photo the following happens:
In Heroku Console
Started POST "/photos" for ...Processing by PhotosController#create as HTML
Completed 422 Unprocessable Entity ... method=POST path="/photos
The browser then shows example.com/photos but the screen is blank.
$(document).ready(function() {
var dropzone;
Dropzone.autoDiscover = false;
dropzone = new Dropzone('#dropform', {
maxFiles: 1,
maxFilesize: 1,
paramName: 'photo[picture]',
headers: {
"X-CSRF-Token": $('meta[name="csrf-token"]').attr('content')
},
addRemoveLinks: true,
clickable: '#image-preview',
previewsContainer: '#image-preview',
thumbnailWidth: 200,
thumbnailHeight: 200,
parallelUploads: 100,
autoProcessQueue: false,
uploadMultiple: false
});
$('#item-submit').click(function(e) {
e.preventDefault();
e.stopPropagation();
if (dropzone.getQueuedFiles().length > 0) {
return dropzone.processQueue();
}
else {
return $('#dropform').submit();
}
});
return dropzone.on('success', function(file, responseText) {
return window.location.href = '/photos/' + responseText.id;
});
return dropzone.on('error', function(file, errorMessage, xhr) {
console.log('error');
});
});
PhotosController
def create
#photo = current_user.photos.build(photo_params)
respond_to do |format|
if #photo.save!
format.html { redirect_to #photo, notice: 'Photo was successfully created.' }
format.json { render json: #photo }
else
format.html { redirect_to new_photos_path, notice: 'Photo was not created'}
format.json { redirect_to photos_path and return #photo.errors, status: :unprocessable_entity }
end
end
end
edit
return dropzone.on('error', function(file, errorMessage, xhr) {
console.log('error');
window.location.href = '/photos/new'
});
results in:
Started POST "/photos" Processing by PhotosController#create as HTML
...Completed 422 Unprocessable Entity in 422ms (ActiveRecord: 14.5ms)
...method=GET path="/photos/new"...method=POST path="/photos"
and then we are back to the blank example.com/photos
redirect_to new_photos_path
should be ->
redirect_to new_photo_path

Using angularjs rails resource query correctly

I am using angularjs-rails-resource and I have set up a service. I have a table of leagues which belongs_to a user so the columns of the league table are id, name, and user_id. I am trying to pull out all the leagues for a specified user.
Here's the code. Every time I use it I am getting all the leagues returned. I am pretty sure I don't have the service defined correctly. Any help would be greatly appreciated.
league_service.js
'use strict';
/* Services */
var ffpServices = angular.module('ffpServices', ['rails']);
ffpServices.factory('League', ['railsResourceFactory', function (railsResourceFactory) {
return railsResourceFactory({
url: '/api/v1/leagues',
name: 'league'
}); }]);
leagues_controller.js
'use strict';
/* Controllers */
var ffpControllers = angular.module('ffpControllers', []);
ffpControllers.controller('LeagueCtrl',
function ($scope, $routeParams, League) {
$scope.leagues = League.query({ user_id: $routeParams.userId });
$scope.leagues.then(function (results) {
$scope.leagues_data = [];
$scope.leagues_data = results;
$scope.lempty = false;
if ($scope.leagues_data.length < 1) {
$scope.lempty = true;
}
}, function (error) {
console.log(error);
});
});
leagues_controller.rb
class Api::V1::LeaguesController < ApplicationController
respond_to :json
def index
#leagues = League.all
render json: #leagues
end
def show
#league = League.find(params[:id])
render json: #league
end
def create
#league = current_user.leagues.new(league_params)
respond_to do |format|
if #league.save
format.json { head :created, location: league_path(#league) }
else
format.json { head :unprocessable_entity }
end
end
end
private
def league_params
params.require(:league).permit(:name)
end
end

rails3 setting a variable in a model using ajax

I'm new to rails, and unable to set a variable in my modal using ajax! My approach is; I first pass it from external javascript (jquery dialog) to my controller, then to my model method as a parameter. Please critique!
My javascript (ajax within jquery-dialog button):
click: function() {
var qtySelected = $("#quantity[data-id='" + prodvarid + "'] input").val();//inputValue check
qtySelected = parseInt(qtySelected); //ensure value is int
$.ajax({
type: "POST",
url: '/line_items',
beforeSend: function(xhr){
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
data: {product_id: prodvarid, qty_selected: qtySelected, remote: true},
dataType: "script"
});
alert("input value is: " + qtySelected); //inputValue check
$("#quantity[data-id='" + prodvarid + "'] input").val(1); //reset default value on submit
$(this).dialog("close");
}
My controller - it receives the :qty_selected value through an ajax POST, to which it is passed into my model using ctlQty:
# POST /line_items
# POST /line_items.json
def create
#cart = current_cart
product = Product.find(params[:product_id])
ctlQty = :qty_selected
#line_item = #cart.add_product(product.id, ctlQty)
respond_to do |format|
if #line_item.save
format.html { redirect_to(store_index_url) }
format.js { #current_item = #line_item }
format.json { render json: #line_item, status: :created, :location => #line_item }
else
format.html { render :action => "new" }
format.json { render json: #line_item.errors, status: :unprocessable_entity }
end
end
end
My model receives the value and sets the local variable current_qty:
def add_product(product_id, qty_selected)
current_qty = qty_selected
if current_qty
current_qty = qty_selected
else
current_qty = 1
end
current_item = line_items.find_by_product_id(product_id)
if current_item
current_item.quantity += current_qty
else
current_item = line_items.build(:product_id => product_id)
end
current_item
end
Upon testing, I receive:
"TypeError (:qty_selected can't be coerced into Fixnum)"
app/models/cart.rb:17in '+'
app/models/cart.rb:17in 'add_product'
app/controllers/line_items_controller.rb:48in 'create'
The error message states that you're trying to use a symbol and a number. Indeed, in the controller, it should be:
ctlQty = params[:qty_selected].to_i # instead of ctlQty = :qty_selected
Also, in add_product, the first 6 lines looks complex, and could simply be written
current_qty = qty_selected || 1

Resources