Link_to RoR with multiple alert box - ruby-on-rails

(New to RoR)I have a link_to in my erb file.
<%= link_to 'Delete', workflows_path+"/destroy/#{workflow.id}?folder=#{#folder_id}", :confirm => "Are you sure you want to delete '#{workflow.name}'?"%>
This will prompt once asking the confirm message.
I want to prompt another alert box on Confirm(On pressing OK) asking "Do you want to delete sub-folders? " with a 'Yes' or 'No' option and pass it to my controller as a boolean(or any type)
(If they choose no, I would redirect the subfolders to parent directory)
Is there an easier way to do this?

in order to have a double-confirmation you would need some javascript.
give your link a CSS class, like 'double-check-workflows'
then add a javascript to your page
$(document).ready(function(){
$("a.double-check-workflows").on('click', function(){
if confirm("first thing to ask"){
target_url = $(this).attr("href")
if confirm("second thing to ask"){
target_url = target_url+"&your_other_param=1"
}
window.location = target_url
}else{
return false
}
})
})
remove the :confirm option from the link helper though cause the js wil handle that
edit
you should really use the routes helper to create the full url instead of adding params as a string as you posted
you could then add a 'delete_sub_folders' param that is default to false/0 and then replace it in the js with .replace() to set it to true/1 if second confirmation returns true

Related

Safe way to load url stored in database?

What is the safest way to load a url saved in database?
window.open("<%=raw #post.url%>");
Doesn't seem to be a good idea.
Since window.open opens a link in new tab there is no direct way to instruct the browser form server side to open a link in a new tab.
But you can apply a little JS hack. In your erb file do it like.
<%= link_to "Post", #post.url, {:target => '_blank', :id => "linktoclick"} %>
<script>
document.ready = function(){
document.getElementById("linktoclick").click();
}
</script>
How are you storing the URL in your database/where are you going to use it?
Assuming #post.url will return the url you want, then something as simple as:
[awesome link name]
html output would be:
[awesome link name]
Could you provide more information on where/how the url needs to be used?
<% unless #post.url.blank? %>
<%= link_to #post.url, 'http://' + #post.url, :target => '_blank' %>
<% end %>
You may want to use this. Unless checks if URL in database is empty or not. If URL is mandatory in database, you may want to remove that part.
Extra, if you need validation for url, you may want to use a validation something like this:
URL = /\A(www.)?([a-zA-Z0-9]+).[a-zA-Z0-9]*.[a-z]{3}.?([a-z]+)?\z/
validates :url,
format: {with: URL, message: 'Invalid url format. Make sure you don\'t have http:// in your link'},
allow_blank: true
So, user will input url without http://, and you will add that http:// in html, as I showed above.

How to toggle a boolean one way with button_to

I have 2 buttons sitting in an if else method and the first button is suppose to allow the user to change a boolean from false to true. Then if the model shows it is true it will show the other button which is a delete button. I cant get the toggle button (top one) to work right the delete is fine. Here is how it stands now.
def which_button(reportapproval)
if reportapproval.user_approved == false
button_to "Approve this Manager?", { controller: "users/reportapprovals", id: #reportapproval.id, action: "#not sure what goes here" }, method: :#not sure what goes here, data: {confirm: "Are you sure you want to give this manager access to your report?" }
else
button_to "Remove this Manager", { controller: "users/reportapprovals", id: #reportapproval.id, action: "destroy" }, method: :delete, data: {confirm: "Are you sure you want to remove this manager's access to your report?" }
end
end
But I keep getting the error Post route no found which i know is not right. I want this to toggle a boolean in the reportapproval model. Please show me what I need to do.
For this you need to make a new action in the users/reportapprovals controller which will set reportapproval.user_approved to true when the user click on the first button. In the first button in the action attribute add the new action created. Also take care to mention the same action in routes. To avoid mentioning the controller and action you can also specify the path of new route created. So this is what you need to do. This can be done using AJAX too or just normally by page reloading.

Rails UJS link_to :remote does AJAX GET and normal <a href> GET

EDIT:
In addition to the helpful comments below, two excellent articles by Steve Schwartz explain everything clearly:
http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
http://www.alfajango.com/blog/rails-3-remote-links-and-forms-data-type-with-jquery/
Rails 3.2.2 / jquery-rails 2.0.1 (uses jquery 1.7.1)
I have link which sends an AJAX request to add additional file upload fields to a form. Everything page-related works correctly - the new form field HTML fragment is retrieved from the server and appended to a div inside the form.
However,
The server receives two GET requests. One is the AJAX request ; the other appears to be the "normal" anchor element GET. I expected the "normal" GET would be stopped by Rails UJS.
Am I supposed to disable the normal link action myself? Can someone please explain what I have misunderstood, and what I should be doing instead [to prevent the second request]?
I've seen this question: Rails 3 UJS - controller gets called twice by link_to :remote. Accordingly, I tried changing the asset pipeline compilation config.assets.debug = false, but it had no effect. Moreover, this is not a double-AJAX GET request, so I think it's a different issue.
Thanks for any help!
Server log snippet:
Started GET "/files/new?asset_number=2" for 127.0.0.1 at 2012-03-23 15:23:27 +0100
Started GET "/files/new" for 127.0.0.1 at 2012-03-23 15:23:27 +0100
Browser HTML:
Add another file
View:
<%= link_to 'Add another file', new_file_path, :remote => true,
:update => 'files',
:position => 'after',
:id => 'add_another_file' %>
Controller's coffeescript:
$( ->
$('a#add_another_file').click( ->
url = '/files/new?asset_number=' + $('#files input').length
$.get(url, ((data) -> $('#files').append(data)), 'html')))
If you're adding a click event to a#add_another_file , then you don't need to use :remote => true , because you're making the Ajax request manually.
Also, the click event should prevent the default action from occurring. This can be accomplished by adding event.preventDefault(); to the beginning of the click event's callback. Note that the callback needs to accept the event argument.
If you want to use the :remote => true option, you should remove the custom click event that you've added. This is because the :remote => true option tells the *jquery_ujs* library to hijack clicks on a#add_another_file. Thus, you needn't make your own HTTP request.
Next, to dictate what's done with the response, bind to the various events that will occur on a#add_another_file, such as success and error.
Here's the full list of Ajax events that you can bind to.
It's actually pretty simple, your remote link_to is sending one request (without params) and you've added a click event on that link to send another one (with params).
You should simplify your link_to as:
<%= link_to 'Add another file', new_file_path, :id => 'add_another_file' %>
Then in your click event you should return false so it doesn't follow the url.
It looks like you're using a lot of unnecessary parentheses in your coffeescript.
$ ->
$('a#add_another_file').click ->
url = '/files/new?asset_number=' + $('#files input').length
$.get url, ((data) -> $('#files').append(data)), 'html'

Ruby/Rails/AJAX/JQuery - On link click, passing a parameter and performing a controller action

I'm trying to use clicking a link to perform and action in my controller called 'yes' but do so client side rather than having to refresh everytime a user clicks.
Before I had an link_to that routed to a action called "yes" and passed the id of a model I have called 'event'
<%= link_to "yes", yes_path(event)%> (in view)
match 'user/:id/yes' => 'user#yes', :as => "yes" {in routes.rb)
The problem issue is that every time the user clicks the link the page refreshes while it performs the yes action, so it will flow alot smoother if I can tell the backend to perform the actions client side.
S0 I found a reference here : execute controller/action from javascript in rails3
and took a look at the documentation : http://api.jquery.com/jQuery.ajax/
And came up with this. Where if the post is successful at the previous route from above change a css class for the link (change color).
$.ajax({
type: "POST",
url: "/user/" + $(this).attr('event') + "/yes/",
success: function(){
$(".like").click(function() {
if ($(this).hasClass("selected")) {
$(this).addClass("selected");
return false; }
});
I also added this is the bottom of the controller that the desired javascript is being used.
respond_to do |format|
format.html { }
format.js
end
So now my link_to looks like this
<%= link_to "yes", yes_path(event), :class => "like", :remote => true %>
But the page is still refreshing and It doesnt look like its calling the AJAX at all.
am I passing the parameter "event" properly as a jquery attribute?
am I calling the link_to properly?
This is my first time so I have no idea what I'm doing wrong, possibly a few things?
I'd really appreciate any help
Is this what you're after?
$(".like").click(function(evt) {
evt.preventDefault();
var $self = $(this);
$.post($self.attr("href"), function(response) {
$self.addClass("selected");
});
});
The first line binds the JavaScript to all elements with a class of like. preventDefault is the preferred way to prevent the default behavior of an anchor tag (navigate to the href). $.post() is shorthand for $.ajax({ type: "POST" }).
Whatever you want to happen after a successful post to the server goes that finally function call. The first argument is the response from the server.
Rich

jQuery ajax call in Rails?

I want to execute a simple thing. When the user clicks the link jQuery needs to generate an Ajax request which sends the id of the link item to a method in the controller. Basically I want a nice looking modal dialog window when the user clicks the delete link. That window needs to contain various info about the deleted items.
E.g.
<%= link_to "Delete", item, :id => "delete" %>
I'm able to select this link with jquery and even to open a popup dialog when the user clicks it. Through application.js but what i really need is jQuery to call my method when the link is clicked and in my method I would answer via format.js. In the js file I place the code to show modal dialog with required parameters. All those actions asynchonous via ajax ofcourse.
I can't generate the ajax request to the method in the controller. Don't know already how to deal with the jQuery.ajax method, especially how to force jQuery to pass the url parameter to the rails method. I watched the railscast and studied the example with .post, but I don't need to submit any form.
Any advise is appreciated.
Thanks
Rails expects a post, with a hidden param.
$('#delete').click(function(e){
e.preventDefault();
$.post($(this).attr('href'), { _method: 'delete' });
});
Rails 3 has an unobtrusive way of doing this using a jQuery plugin:
http://github.com/rails/jquery-ujs
Once you have that loaded into your layout (with jQuery 1.4.1 or newer), you can do interactions like this pretty easily.
<%= link_to 'delete', item, :remote => true, :method => :delete,
:confirm => 'Are you sure?' %>
In Rails 3 all this does is add some HTML attributes to your link. These get caught by live handlers in the jQuery plugin. It's easy to use this behavior in a Rails 2 application, though:
<%= link_to 'delete', item, :'data-remote' => true, :'data-method' => :delete,
:'data-confirm' => 'Are you sure?' %>
Note that you need to have the jQuery plugin loaded in your view.
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to
If you need the initial response to be a modal instead of an alert, you could make the first link a bit simpler:
<%= link_to 'delete', modal_confirm_item_url(item), :'data-remote' => true %>
You could link it to some pre-existing member action. Or since you may eventually want to use .js responses from those actions to serve other ajax requests, it may make sense to create a new action to handle this behavior.

Resources