Rails 3 - remote delete - ruby-on-rails

In an ERB Rails view
<%= link_to("Destroy", foos_path(1), :method => :delete, :confirm => "Are you sure?") %>
With a link_to like the above you can process the delete for a foo with an ID of 1.
How do make it remote and (a) still control being redirected to a page of my control or (b) call custom JavaScript (the goal of which would be jQuery to refresh a list)

Add :remote => true to the link_to will create a remote link.
In your controller method at the end put
respond_to do |format|
format.js { render "my_method"}
end
You can omit the name of the ajax file if it's the same name as the method.
In my_method.js.erb simply call javascript functions, and you can embed erb ie:
$("#someDiv").load(<%= #some_value $>);
You can redirect to another page using standard javascript/jquery if you choose.

Related

Rails link_to :confirm for a specific page

I'm new to Ruby on Rails and would like to know that, if there is a way to strict link_to :confirm for a specific page. Because I'm putting this in every page, but I don't want it to show a confirm message in every page.
I'm adding the code here as well, but the formate it's incorrect in the textbox.
link_to "Home",'/', :confirm => 'Clicking OK Will Discard Any Unsaved Changes. Click Cancel To Return To The Home Page.'
You can make a helper like this to restrict by controller_name and action:
def link_home(link_options = {})
unless controller_name.eql?('some_controller') and action_name.eql?('some_action')
link_options.merge!{:confirm => 'Clicking OK Will Discard Any Unsaved Changes. Click Cancel To Return To The Home Page.'}
end
link_to "Home",'/', link_options
end

rails 3 - link_to to destroy not working

I am trying to create a destroy link to my users controller, I am also using devise.
Here is my code -
View
<%= link_to 'Delete User?', child, :confirm => "Are you sure you want to delete #{child.full_name}?", :method => :delete, :class => "user-additional", :style => "font-size:12px;font-weight:normal;" %>
Controller
def destroy
if #user = User.find(params[:id])
#user.destroy
respond_to do |format|
format.html { redirect_to account_index_path }
format.xml { head :ok }
end
end
end
Routes
devise_for :users
resources :users, :except => [:new]
The link translates to localhost:3000/users/10
When clicked this opens the users show instead of deleting them
Any ideas ?
Destructive actions should be performed as a form submission - http://www.w3.org/2001/tag/doc/whenToUseGet.html#checklist
use button_to (passing a :method => :delete) instead and style the button appropriately.
Actually I just had the exactly same problem yesterday
Try this:
<%= button_to "delete", your_object, :method=>:delete, :class=>:destroy %>
It works (for me at least)
In case that you are using jQuery instead of Prototype, you are probably missing a javascript file.
You can find details on how to add it to your project from the jquery-ujs GitHub page or from episode 205 of the Railscasts.
At a guess I think it is because in Rails 3, unobtrusive javascript is now used for functionality such as this (Rails 2 would output a bunch of nasty inline javascript for your code, Rails 3 puts the javascript in an external file, and uses HTML5 data- attributes to interact with that.)
To solve this you need to include <%= csrf_meta_tags %> in your page header to reference the external javascript. It also deals with XSS issues.
Some details here: Delete link sends "Get" instead of "Delete" in Rails 3 view
If you are using jQuery, make sure you have something like this:
<script type="text/javascript">
// this allows jquery to be called along with scriptaculous and YUI without any conflicts
// the only difference is all jquery functions should be called with $j instead of $
// e.g. $jQ('#div_id').stuff instead of $('#div_id').stuff
var $jQ = jQuery.noConflict();
</script>
follow the steps in the installation part rails/jquery-ujs
add <%= javascript_include_tag "application" %> in your layout file.
If you haven't included jquery and jquery-ujs in your app , the default link_to default coming with scaffold wont work!
I had the same issue.It got solved after including both these js!
Also if you get this problem in production mode, it may be because you have not compiled the assets. See http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets
Worked for me with confirmation message.
<%= button_to 'Destroy', {action: :destroy, id: version.id}, onclick: 'return confirm("Are you sure?")', method: :delete %>

Generate PDF file using AJAX call

I'm trying to generate a PDF file using AJAX call in Rails3. The following code generates a PDF file which I have created using PRAWN gem.
<%= link_to "Generate pdf", books_path(#book, :format => 'pdf') %>
I do not want user to view the PDF until they order it. So, the goal is to create a PDF file in the server.
Any ideas or thoughts much appreciated.
Use this, make sure your remote action does not return the PDF, but simple generates and stores it on the server.
link_to "Generate PDF", prepare_books_path(#book), :remote => true, :method => :put
This will work in Rails 3. If you're using jQuery, make sure to read this article on how to set things up correctly.
Your controller action may look like this:
def prepare
# Do your thing to generate the PDF
render :text => "PDF Generated", :status => 200
end
I used the PUT-method because you are altering the state of your data (e.g. you are generating something new, you don't want a bot or crawler to automatically call that).
Firstly, it beats me why you would do something on a request like generating a PDF, when the user is not expecting that action. Isn't better to only generate the pdf when the user requests for it?
Thanks Ariejan.
I modified your code as following and it did just what I wanted.
<%= link_to "Generate Story Book", pdfbook_stories_path(:format => 'pdf'), :remote => true %>
And for the controller,
def pdfbook
#stories = current_account.stories
respond_to do |format|
format.pdf {}
end
end

Rails: send_file not causing download, links to 'show' controller method instead

First time using rails, I'm trying to create a download link to get something off the file system.
In my view, I've got
<%= link_to 'Show', upload, :method => :download %>
and my 'download' method in my controller looks like:
def download
#upload = Upload.find(params[:id])
send_file '/data_store/50692.pdf'
This is needed because I have restrictions on who can view this pdf, but on this page, I get linked to
http://localhost:3000/uploads/10
(10 is the id of this 'upload')
and on that page, I get the error
Unknown action
No action responded to 10. Actions: clearance, create, destroy, download, edit, index, is_admin, new, show, su_required, and update
I want it instead to stay on the same page, and offer the user a download prompt, but I'm not sure what I'm doing wrong.
Ideally you should be looking into a Ajax call if you'd want to stay on the same page and offer the user a download prompt, but the code given below would also work. Upon clicking the "download" link it'll open a new tab/window,offer the user a download prompt and close the tab/window.
Also the :method parameter to link_to tells it which HTTP method (POST,GET,DELETE,PUT) to use. To reference the "download" method in your controller use the :action parameter.
view
----
<%= link_to 'Show', upload, :action => :download, {:target => "_blank"} %>
controller
----------
return send_file '/data_store/50692.pdf', :type => "application/pdf", :filename => "50692.pdf"
I think it is a problem in the calling download method.
Try this one
<%= link_to "Show",:controller=>'controllername',:action=>'download',:id=>upload.id %>
You must pass your controller name in the place "controllername".

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