Modal Pop up window on Rails Controller Action - ruby-on-rails

In my customer index view if I click on delete customer button, the following actions take place in my Customers controller delete method.
Customers_controller.rb
class CustomersController < ApplicationController
.
.
def destroy
if Customerarticle.where(author_id: params[:id]).count > 0
#####I need the logic here to display a modal window on my index page of customers here#####
else
Customer.find(params[:id]).destroy
flash[:success] = "Customer deleted"
# debugger
redirect_to customers_path
end
So based on my condition if it's true means customer can't be deleted, and that message to be displayed in a modal pop up window on Customers index page itself, how to achieve it ?

I suggest you issue an ajax request when the button was clicked and make it redirect to your destroy action. Then, within the controller do your logic and simply return a true/false (or whatever else you need) and use it in your JS callback.
For example:
In your view.js
$(document).ready(function(){
$("#delete_button").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/URL/TO/CONTROLLER",
data: { id: someID},
success: function(result){
if(result == true) {
// Do something
} else {
window.location.replace(result);
}
}});
});
});
In your controller:
def destroy
if Customerarticle.where(author_id: params[:id]).count > 0
return true
else
Customer.find(params[:id]).destroy
flash[:success] = "Customer deleted"
return customers_path
end
end
This should work just fine. Remember, it definitely needs some re-work and adjustments :)

Related

Rendering template with json params

I have new and create actions like this:
def new
#foo = Foo.new
end
def create
#foo = Foo.new(foo_params)
respond_to do |format|
if #foo.save
format.html { redirect_to root_path }
else
format.html { render :new } //**this line I want to send params**
end
end
end
I have a jbuilder file to new action like this:
new.json.jbuilder
json.foo do
json.a "Some important info"
json.b "Some important info"
end
And rails can't read this file after create's validation fails. How to render a view template (like render :new) and send some json data in this view?
I have a js calling like this:
var json_url = window.location.href + ".json";
var foo;
$.ajax({
url: json_url,
dataType: 'json',
async: false,
success: function(data) {
foo = data.foo;
}
});
If you want Rails to render a file, you'll need to remove the call to redirect_to as it will effectively prevent any rendering.
Furthermore, if you don't want the controller to respond to different formats, it's better to skip the call to respond_to, too.
If you just call render action: :new, the view template will have access to all controller instance variables (like #foo):
json.foo do
json.a #foo.a
json.b #foo.b
end

Rails Ajax Call : Pass JSON to separate controller method

Hey everyone I am having an issue setting up my app. It uses the shopify API and essentially what it does is grab some data via a view and sends it to the controller but I am having issues passing it to another method in the controller to use the API to save the data.
Here is my code :
Controller
class BuilderController < ShopifyApp::AuthenticatedController
def index
urlval = request.fullpath
#urlCheck = urlval.split('/').last
end
def show
url = request.fullpath
#urlID = url.split('/').last
#customers = ShopifyAPI::Customer.search(query: "id:"+ #urlID)
#need to get a way to retrieve the ajax call info here to pass into the update
end
def updateCustomer(notes)
#customers.each do |cus|
cus.note = notes
cus.save()
end
end
def new
notes = params[:notes]
updateCustomer(notes)
render json: notes
end
end
View
<button id="test">TEST</button>
<script>
var butt = document.getElementById('test');
butt.addEventListener("click",function(){
$.ajax({
url: "/builder/new",
type: "GET",
data: {
"notes": [
"test",
"test2"
]
},
success: function(data,text,xhr) {
console.log(text);
console.log(xhr);
console.log(data);
alert('successfully');
},
error: function(data,error){
console.log(data);
console.log(error);
alert("help");
}
});
});
</script>
Rather than a fully separate method, have you looked into the
respond_to method? http://api.rubyonrails.org/classes/ActionController/MimeResponds.html#method-i-respond_to
You could do (assuming html is the primary request type, change if it isn't):
def index
respond_to do |format|
format.html { actions }
format.json { actions }
end
end
This the method we use to accommodate different request types within the same action. Please let me know if I've misinterpreted your question.
you can use this
update_all(updates) public
Updates all records with details given if
they match a set of conditions supplied, limits and order can also be
supplied. This method constructs a single SQL UPDATE statement and
sends it straight to the database. It does not instantiate the
involved models and it does not trigger Active Record callbacks or
validations.
http://apidock.com/rails/v4.0.2/ActiveRecord/Relation/update_all
def new
notes = params[:notes]
#customer.update_all({note: notes})
respond_to do |format|
format.html {}
format.json { json: #customer.json }
end
end

AJAX on dynamic class value for Rails

Short version:
If I have
.favorite-link
= link_to some_path, class: (#condition ? "favorited" : "") do
.star-image
routes.rb
resources :hacks do
post "favorite", on: :member
end
hacks_controller.rb
def favorite
#favorite = Favorite.find_or_initialize_by(user_id: current_user.id, hack_id: params[:id])
if #favorite.persisted?
#favorite.destroy
respond_to do |format|
format.js
end
else
#favorite.save
respond_to do |format|
format.js
end
end
end
favorite.js.coffee
$('.favorite-link a').toggleClass("favorited")
This last bit of code changes EVERY instance. How do I toggle just the one I clicked? Doing `.on 'click', -> $(this).toggleClass("favorited") does weird stuff, like change it only every other time I click it. Plus, the render js is not suited for that way.
Or perhaps a better way to accomplish toggling the class value is: how do I toggle the star using ajax (i.e. make the page evaluate #condition again after clicking the link?)
Irrelevant to the core of the question, but FYI:
SCSS
.favorite-link {
a.favorited {
.star-image {
background-image: url('star-on.png');
}
}
.favorite-link {
a {
.star-image {
background-image: url('star-off.png');
}
}
}
Use jQuery to add the class as part of your Ajax response handler:
$(".star-image").addClass("favorited");
There is also .toggleClass and .removeClass to fill out your implementation.

Update view with Rails (Ajax)

I have an app of reservations. The thing is that admins can view reservations by date. This is done by an input with has appended datepicker. Each time the user picks a date, the view is updated (that's the idea). However, until now I don't know how to update the view with the new data. This are my methods:
def index
#reserva = Reserva.new
#reservas = Reserva.all.joins(:user).where.not(:user_id => session[:user_id])
#mis_reservas = Reserva.where(:user_id => session[:user_id])
end
def actualizar_por_fecha
if params[:fecha] != nil
#mis_reservas = Reserva.find_by_fecha(params[:fecha])
#reservas = Reserva.find_by_fecha(params[:fecha])
respond_to do |format|
format.html { render 'reservas/index' }
end
end
end
And the CoffeeScript code is the following:
$("input#ver_reservas_fecha").on "change", (e) ->
$.ajax
url: "actualizar_lista_de_reservas_por_fecha"
data:
fecha: $("#ver_reservas_fecha").val()
success: (data) ->
console.log(data)
return
return
Thanks in advance
Refer to this question to know how to create a partial and refresh the div after ajax call.
How do I render partial via ajax in rails3 and jQuery
Also refer to this to understand it a bit more
http://richonrails.com/articles/basic-ajax-in-ruby-on-rails

Why is AJAX in Rails 3 so hard? Or, what am I doing wrong?

None of the tutorials I seem do what I'm trying to do. Very simply, I want a user to be able to submit a POST request to a controller (to "LIKE" a video) and have the controller respond back with a JSON object. Any help would be appreciated.
Thanks
EDIT Because SO is messing the formatting up, here is a gist of my code too:
https://gist.github.com/813503
Here is my controller:
class LikesController < ApplicationController
before_filter :get_ids
respond_to :json, :js
def videolink
results = {}
# check to see if the user has liked this videolink before
if current_user
liked = Like.video?(current_user, #vid_id)
results["status"] = "OK"
results["liked"] = liked
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
def update
results = {}
if current_user
results["status"] = "OK"
else
results["status"] = "Error"
results["message"] = "User not logged in"
end
respond_with( results.to_json )
end
private
def get_ids
#vid_id = params[:videolink_id]
end
end
Here is my JS file:
$("#likeVideo").click(function() {
$.ajax({
contentType: "application/json",
data: { game_id: game_id, videolink_id: current_video["videolink"]["id"] },
dataType: "json",
type: "POST",
url: "/likes/" + game_id,
success: function(data) {
console.log("Success", data);
}
});
return false;
});
My routes:
resources :likes do
collection do
get "videolink"
end
member do
post :update
end
end
And here is the error I get:
NoMethodError
in LikesController#update
undefined method `{"status":"OK"}_url' for #<LikesController:0x0000010178be58>
If you want to send back custom JSON, Instead of respond_with(results.to_json)... just render the text
render :text=>results.to_json
The responds_with is a way for you to easily send back objects, with their location (url). So that's why your error is telling you that that '_url' is invalid.
More info on responds_with, courtesy of http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering
If another format was requested, (i.e.
:xml or :json)
If it was a GET request, invoke the :to_format method on the resource and
send that back
If the resource has validation errors, send back the errors in the
requested format with the
:unprocessable_entity status code
If it was a POST request, invoke the :to_format method on the resource
and send that back with the :created
status and the :location of the new
created resource
Else, send back the :ok response with no body

Resources