ruby on rails destroy without javascript, the simple way

Ok, I know this is an old issue, there’s a railscasts episode about this but I think it’s too complicated (though I like it :p). So instead I use a simpler way, it goes like this

instead of doing

<%= link_to "Destroy", @model, :confirm =>"Are you sure?", :method => :delete %>

I ended up using

<%= link_to "Destroy", model_path(@model, :destroy => true),
 :confirm =>"Are you sure?", :method => :delete %>

notice the different, I only change @model to model_path(@model, :destroy => true) which will generate an url like /models/xx?destroy=true. Now if the user have javascript disabled in their browser, this link will just get them to the show action, and this is where we filter wheter the user want to show or destroy the model based on the existence of destroy param. In my show action it’s just a simple if condition

def show
  @model = Model.find(params[:id])
  if params[:destroy]
    render 'confirm_destroy' and return
  end
end

and in the confirm_destroy.html.erb file is basically the same with the one in the railscasts episode, instead I’ll paste in

<% form_for :model, :url => model_path(@model), :html => { :method => :delete } do |f| %>
  <h2>Are you sure you want to destroy this model?</h2>
  <p>
    <%= submit_tag "Destroy" %>
    or <%= link_to "cancel", models_path %>
  </p>
<% end %>

and that’s it, if the user has javascript enabled it’ll do the usual and if the user have javascript disabled it’ll show them the confirmation page.

Hope this useful. :-)

Advertisements

3 thoughts on “ruby on rails destroy without javascript, the simple way

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s