I have delete action in my controller, this is the code in pickups_controller.rb
def delete
#pickup = Pickup.find(params[:id])
if !#pickup.nil?
#pickup.destroy
render json: { success_message: "Success!, Pickup is deleted." }, status: :ok
end
end
I call the delete action using javascript json by pressing a button using assets/javascripts/pickups.js
document.addEventListener("DOMContentLoaded", function(event) {
var xhttp = new XMLHttpRequest();
// delete the pickup you choose
$('.removepickup.btn.btn-primary').on('click', function() {
var pickup_div = $(this).parents('.removepickupparent');
var pickup_id = pickup_div.attr('id');
var x = "../deletepickup?id=" + pickup_id;
$.ajax({
type: "POST",
url: x,
success: function(data) {
var success = data.success_message;
$(".successr"+ pickup_id).text(success).show(0).delay(1000).hide(0);
setTimeout(function () {
location.reload();
}, 1000);
},
error: function (xhr, ajaxOptions, thrownError){
if(xhr.status==404) {
$(".errorl"+ pickup_id).text("Fail!, pickup Is Already Deleted Before").show(0).delay(1000).hide(0);
setTimeout(function () {
location.reload();
}, 2000);
}
}
});
});
// when pressing on this button, it redirects you to create pickup page
$('.addpickup.btn.btn-primary').on('click', function() {
var success = "Redirecting to add pickup Page"
$(".successp").text(success).show(0).delay(2000).hide(0);
setTimeout(function () {
$(location).attr('href', '../createpickup');
}, 2000);
});
});
the function is working great, but when adding 4 lines extra code inside the delete action, it doesn't work, here's the code after adding 4 lines of extra code inside my delete action, and the action is not working.
def delete
#pickup = Pickup.find(params[:id])
if !#pickup.nil?
# the start of the extra code
#trip = Trip.find(#pickup.trip_id)
if !#trip.nil?
#trip.seatsno = #trip.seatsno + 1
#trip.save
end
# the end of the extra code
#pickup.destroy
render json: { success_message: "Success!, Pickup is deleted." }, status: :ok
end
end
any solutions please? .. knowing that I'm still beginner in Ruby on Rails
Note:
I used byebug, and when reaching the first line in the etra code I got this error in the local server terminal
"request.env["action_dispatch.show_detailed_exceptions"] ||= show_detailed_exceptions?"
Use the find_by instead of the find method. The find' method raises the exception if a particular record is not found, whilefind_by` returns nil.
Usage:
find_by(id: params[:id])
This answer is more of a refactor suggestion than the actual answer, but it may fix your problem as well.
You can refactor your action to this:
def delete
#pickup = Pickup.find(params[:id])
# no need to test #pickup.nil? here because `find` method raise
# an ActiveRecord::RecordNotFound error if the record is not found
# which should be caught by ApplicationController to render a 404
if #pickup.destroy
#pickup.trip.update_attributes(seatsno: #pickup.trip.seatsno + 1)
render json: { success_message: "Success!, Pickup is deleted." }, status: :ok
else
render json: { error_message: "Error, Pickup could not be deleted." }, status: 409
end
end
Even better, move the concern of incrementing seatsno to the Pickup model:
# app/models/pickup.rb
after_destroy :increment_trip_seatsno
def increment_trip_seatsno
self.trip.update_attributes(seatsno: self.trip.seatsno + 1)
end
And remove the concern from the Controller. This way, every time a Pickup record is destroyed via Rails (console or other places in your app), the trip will be updated accordingly.
Related
I have one annoying problem that I am not able to solve.
I am generating CRUD operations in my Symfony project. I made an AJAX request for Add method which works as it should.
After that I have created AJAX request for Delete method.
When I add my new entity object the table is reloaded without page refresh.
Problem is that if I click delete after it's added it throws an error that ID is not found.
/**
* #Route("/user/{id}", name="user_delete", options={"expose"=true})
*/
public function delete($id)
{
$em = $this->getDoctrine()->getManager();
$$user = $em->getRepository(User::class)
->findOneby(['id' => $id]);
if (!$user) {
throw $this->createNotFoundException('No User found for id '.$id);
}
$em->remove($user);
$em->flush();
return $this->json(["message" => "SUCCESS"]);
}
So, for example I have added entity with ID = 2 . DIV is reloaded. Now I click in delete of 2 and it's says:
No user found for id 1
Problem is it always fatches the last ID I deleted after page refresh.
Now, if I refresh the page and then try delete it will catch ID = 2 and delete it. Now, I add ID = 3 without refreshing the page and it will throw:
No user found for id 2
I think maybe it has to do with my add form:
Add form:
$('#form-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/subscription/add',
data: $('form#subscription-form').serialize(),
processData: false,
success: function () {
$("#user-table").load(location.href + " #user-table");
$('#addUser').modal('hide');
displayNotif('success', 'check', 'User created successfully');
},
error: function (xhr, status, error) {
var ErrorMessage = JSON.parse(xhr.responseText);
$('#general-error').html(ErrorMessage.message);
}
});
});
Can someone please help?
$(document).ready(function () {
$('.user_delete').on('click', function () {
let removeUrl = $(this).attr('data-remove-url');
$('.remove-user').attr('data-remove-url', removeUrl);
});
$(".remove-user").click(function (e) {
let removeUrl = $(this).attr('data-remove-url');
e.preventDefault();
$.ajax({
url: removeUrl,
type: 'DELETE',
success: function()
{
$("#user-table").load(location.href + " #user-table");
$('#confirmDelete').modal('hide');
displayNotif("danger", "warning", "User deleted successfully");
}
});
});
});
I am adding everything so you can get an idea of what I am doing:
<a href data-toggle="modal" data-target="#confirmDelete" data-remove-url="{{ path('user_delete', {'id':user.id}) }}" class="btn user_delete">x</a>
Option 1:
The click event is not working properly for the delete button.
Try to replace
$(".remove-user").click
With
$(".remove-user").on(“click”
Option 2:
data-remove-url
this attribute is not updated accordingly. Check your DOM to verify
How to auto refresh a partial view?
public PartialViewResult Chat(string people)
{
if (User.Identity.IsAuthenticated)
{
var model = new MessageVM()
{
realReceiver = people,
messageList = db.messages.Where(x => x.sender == User.Identity.Name || x.sender == people).ToList().Take(30)
};
return PartialView("_Chat", model);
How to auto refresh this partialview
Just to test quickly, change your controller action for Chat from POST to GET. Then call it by pasting the address in your browser address bar. You can include the value for people parameter like this at the end of the URL:
?people=valueForPeople
Check the returned HTML and ensure that is what you are expecting. Once you have confirmed the action is returning the HTML you want, then you can change back to POST if you prefer. Then use the jQuery code below.
One option is to setup a timer on the client side which will call your controller and then you can do whatever you need with the returned data.
window.setInterval(function() {
// send get request to server
$.ajax({
url: '/Chat',
type: "POST", // or use GET
data: whateverYourArgumentsAre, // people
success: function (partialViewHtml) {
$("#divLt").html(partialViewHtml);
});
},
error: function () {
alert('Something went wrong');
}
});
}, 5000); // Every 5 seconds, 5000 ms
Html.Action("Messages","Chat", new { people= "give some data"})
I'm trying to get a little red notifications circle to update dynamically in my Rails chat application using Action Cable. The problem is that sometimes when a message is sent, it seems to trigger the receive function more than once. I'm pretty sure I have the subscriptions defined correctly, but something is going wrong.
Here I make sure to create the subscriptions using the chat_id parameter. The same parameter is used in the submitNewMessage function
assets/javascript/channels/chat.js
$(document).on('turbolinks:load', function() {
submitNewMessage();
$.ajax({
type: "GET",
dataType: "json",
url: "/chats",
success: function(data){
$.each(data, function(i, chat){
App['chat' + chat.id] = App.cable.subscriptions.create({
channel: "ChatChannel",
chat_id: chat.id},
{ received: function(data){
# Code to update notifications
}}
});
}
}
});
function submitNewMessage(){
$('#message_text').keydown(function(event) {
if (event.keyCode == 13) {
var text = event.target.value
App['chat' + chat_id].send({text: text})
$('#message_text').val(" ")
return false;
}
});
}
});
And in the subscribed method I also use the chat_id params
channels/chat_channel.rb
class ChatChannel < ApplicationCable::Channel
def subscribed
stream_from "chat_#{param['chat_id']}_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def receive(payload)
Message.create(user_id: current_user.id, chat_id: params["chat_id"], text: payload["text"])
end
end
How could the received function in chat.js be triggered more than once when a new comment is triggered?
Turns out that the Ajax request was creating a double of each request, when I visited other pages. I fixed it by adding
if (App['chat' + chat.id] == undefined){...
before creating the subscriptions. This way it only creates a subscription if it doesn't already exist.
i am making a calendar, and i make an ajax request on page load to get the some data from the rails db.
the ajax call successfully receives object on page load.
when i click on next or previous button to get the previous months data or next months data, even though the ajax call happens, no data object is receiving on success callback
i receive a set of objects which i access like the code below but only for the page load ajax call, the ajax call gets a status code 200 - OK each time but no json object is received on next requests.
In other words, console.log(data) only works on the page load event while console.log($month) works everytime
UPDATE: using the dev tools, i can see the response data, but they are not accessible from success in ajax...
UPDATE 2: when i uncomment error i get the message "The error code is: OK"
my ajax code looks like this
function retrieve($month) {
console.log($month);
var jsondata = {
events: {
month: $month,
}
}
$.ajax({
cache: false,
type: "POST",
url: "/events/find",
data: jsondata,
dataType: json,
statusCode: {
200: function() {
//alert("200");
},
202: function() {
//alert("202");
}
},
success: function(data) {
//alert("Data Send!");
//var data = JSON.stringify(data);
console.log(data);
for (var i = 0; i < data.length; i++) {
var day = data[i].date.substring(0, 2);
$("td[data-day='" + day + "']").addClass('added');
}
},
error: function(xhr) {
//alert("The error code is: " + xhr.statusText);
}
});
}
events_controller
def find
params = event_params
#events = Event.where('date LIKE ?',"%#{params[:month]}%")
respond_to do |format|
if #events
format.json {
render json: #events.to_json
}
else
render 'index'
end
end
end
private
def event_params
params.require(:events).permit(:date, :timerange,:month)
end
example response from rails log
Started POST "/events/find" for ::1 at 2015-08-16 16:09:59 +0300
Processing by EventsController#find as */*
Parameters: {"events"=>{"month"=>"September"}}
Event Load (0.1ms) SELECT "events".* FROM "events" WHERE (date LIKE '%September%')
Completed 200 OK in 2ms (Views: 0.1ms | ActiveRecord: 0.1ms)
Just for future reference for someone who might need this.
The problem was the dataType: json
it seems that when rails converted the results to json, they were invalid for jquery thus the error event was fired.
removing dataType.json from the ajax request fixed my problems.
I'm newbie with Rails
My purpose is insert song_id and title which received from Javascript via AJAX POST into Database (MySQL)
In my javascript file
var song_id = "23f4";
var title = "test";
$( document ).ready( function() {
jQuery.ajax({
url: 'create',
data: "song_id=" + song_id + "&title=" + title,
type: "POST",
success: function(data) {
alert("Successful");
},
failure: function() {
alert("Unsuccessful");
}
});
} );
In my editor_controller.rb
class EditorController < ApplicationController
def new
#song = Song.new
end
def create
logger.debug("#{params[:song_id]}")
logger.debug("#{params[:title]}")
#song = Song.new(song_params)
if #song.save
redirect_to root_path
else
flash[:notice_song_failed] = true
redirect_to root_path
end
end
private
def song_params
params.require(:song).permit(:song_id, :title)
end
The problem is when I running the Rails app with this code, the Console notices me that
ActionController::ParameterMissing at /editor/create
param is missing or the value is empty: song
I'm trying to use
private
def song_params
params.require(:song).permit(params[:song_id], params[:title])
end
but it doesn't work and notices me the same, moreover in the terminal log told me below
Started POST "/editor/create" for ::1 at 2015-04-01 01:07:23 +0700
Processing by EditorController#create as /
Parameters: {"song_id"=>"23f4", "title"=>"test"}
23f4
test
Completed 400 Bad Request in 1ms
Do I missed something in my code, Thanks for Advance.
You are not sending a song parameter at all. It looks like you need to update the data line in the jQuery.ajax call to include the song parameter like so:
data: {song: {song_id: song_id, title: title}}
This:
params.require(:song).permit(params[:song_id], params[:title])
is saying "require the 'song' parameter, and allow 'song_id' and 'title' through. If you don't pass a song parameter, you'll get a bad request.
You can either:
Change that line of code to remove the require on 'song'
or
Like #infused says, change your ajax call to send a song JSON object.