Rails GET method is called instead of DELETE - ruby-on-rails

I am trying to delete a record using :method => :delete but its calling GET instead. It redirects to show and displays 404 not found. But if i go back and refresh, the record is acctualy deleted.
<% #photos.each do |photo| %>
<div class='photogallery'>
<%= link_to image_tag(photo.image_url(:thumb)) if photo.image? %>
<div class="name"><%= photo.caption %></div>
<div class="actions">
<%= link_to "edit", edit_admins_photogallery_path(photo) %> |
<%= link_to "remove",admins_photogallery_path(photo), :method => 'delete',:confirm => 'Are you sure?' %> |
</div>
</div>
<% end %>
application.js
//= require jquery
//= require jquery_ujs
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require dataTables/jquery.dataTables
//= require bootstrap
//= require bootstrap-select
//= require jquery.timepicker
//= require jquery.ui.tabs
//= require jquery.ui.datepicker
//= require jquery.ui.accordion
//= require jquery.ui.autocomplete
//= require strftime-min.js
//= require turbolinks
//= require_tree .
i have included in my layout file and its been loaded fine.
<%= csrf_meta_tag %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
The weird part is it used to work fine few days back,now it has stopped working for all the controllers.
edit: routes.rb
devise_for :users
root 'index#index'
resources :reprint
devise_scope :user do
get "/admins/", :to => "devise/sessions#new"
end
namespace :admins do
resources :location,:dashboard,:lodge,:room,:booking,:rate_calendar,:photogallery
end
resources :index do
collection do
match 'search' => 'index#search', via: [:get, :post], as: :search
match 'location' => 'index#location', via: [:get, :post], as: :location
match 'add_cart' => 'index#add_cart', via: [:get, :post], as: :add_cart
end
end
resources :room_availability
edit: photogallery_controller.rb
def destroy
#photos = Photogallery.find(params[:id])
if #photos.destroy
redirect_to admins_photogallery_path, notice: "Photo was successfully destroyed."
else
render :action => 'index'
flash[:error] = "Photo could not be deleted."
end
end

I ran across the same problem and when I changed link_to to button_to everything started working correctly. Maybe because link_to is mainly used for GET calls and button_to for POST calls (in my case DELETE also).

def destroy
#photos = Photogallery.find(params[:id])
if #photos.destroy
redirect_to admins_photogalleries_path, notice: "Photo was successfully destroyed."
else
render :action => 'index'
flash[:error] = "Photo could not be deleted."
end
end
I believe you have it set up correctly, you just made a typo in the redirect_to call. admins_photogallery_path is the show page. admins_photogalleries_path is the index page. There's no way you're making a GET request and reaching the destroy method unless you specified that specifically in the routes. The GET and DELETE verbs both talk to the same path - if you were indeed using a GET request, you'd simply go to the show page and nothing would happen. That anything got deleted at all suggests that the DELETE request is being made successfully.

Related

Why isn't this ajax:success call working?

I know there's a ton of threads about this, but I can't seem to figure out what's broken here. I have a remote link that calls a like method.
When I click the like link...
What's happens:
The like is created (as expected).
The page does not refresh (as expected).
What should happen:
Everything above, plus the content change in like.js.erb. I've added a console.log to this file and it does not show up when clicking the like link.
_like.html.erb
<% recipe = recipe || #recipe %>
<%= link_to unlike_recipe_path(recipe), remote: true, class: "recipe-card__like like" do %>
<i class="heart icon"></i>
<% end %>
note: the partial is rendered both on a show page and within an index, which is why I use the || statement.
like.js.erb
$('.like').bind('ajax:success', function(){
console.log('like clicked');
$(this).closest('.like').hide();
$(this).closest('.like-container').html('<%= escape_javascript (render partial: 'unlike', recipe: #recipe ) %>');
});
routes.rb
resources :recipes do
resources :likes
member do
get "/like", to: "recipes#like"
end
end
recipes_controller.rb
def like
#recipe = Recipe.find(params[:id])
#like = #recipe.likes.create(recipe_id: #recipe.id, user_id: current_user["uid"])
respond_to do |format|
format.html
format.js
end
end
application.js
//= require jquery
//= require jquery_ujs
//= require rails-ujs
//= require turbolinks
//= require semantic-ui/sidebar
//= require_tree .
You can do it in many ways using JS/Html/Ajax.
#like.js.erb
#if wanna validate the request success or fail use #like
# just make sure #like is not string type otherwise it will always success in JS file.
if("<%= #like %>"){
console.log('like clicked');
$(this).closest('.like').hide();
$(this).closest('.like-container').html('<%= escape_javascript (render partial: 'unlike', recipe: #recipe ) %>');
}
Also, in controller no need recipe_id: #recipe.id. It's supposed to assign automatically.
#like = #recipe.likes.create(user_id: current_user["uid"])
Like I said in comment, the moment you .bind('ajax:succeed') is already to late because this file is indeed the result. Your erb file will be filled before rendering the output so you could do
<% if #result == "success" %>
console.log('like clicked')
$(this).closest('.like').hide();
$(this).closest('.like-container').html('<%= escape_javascript (render partial: 'unlike', recipe: #recipe ) %>');
<% else %>
console.log('something went wrong, this person has to many likes')
<% end %>
where #result is your controller variable
My link was calling the unlike method instead of the like method. Simple typo.
Original
<% recipe = recipe || #recipe %>
<%= link_to unlike_recipe_path(recipe), remote: true, class: "recipe-card__like like" do %>
<i class="heart icon"></i>
<% end %>
What it should be
<% recipe = recipe || #recipe %>
<%= link_to like_recipe_path(recipe), remote: true, class: "recipe-card__like like" do %>
<i class="heart icon"></i>
<% end %>

Destroy Method in Ruby Application does not work

For my ruby on rails application the destroy method doesn't work.
This is how the controller.rb looks like:
def destroy
#post = Post.find(params[:id])
#post.destroy!
redirect_to '/posts/new(.:format)'
end
The show.html.erb:
<div class="btn">
<%= link_to "Delete", :method => :delete %>
</div>
And the application.js:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
When the post url is http://localhost:3000/posts/bestpostever
and I click the delete button, I get directed to http://localhost:3000/posts/bestpostever?method=delete but that's it. The post still gets shown.

Rails destroy does not work and forwards to a wrong link

I am totally new to rails and struggle with the easiest stuff. I have the following problem:
When I try to destroy a search (from my model search) it does not work and I get redirected to "/search.48 (the search with id 48). It gives me the notice "We're sorry, but something went wrong." and in the console it says something with POST. Neither the search is deleted nor the redirect_to search_path is working. What am I doing wrong?
This is my controller:
def show
#searches = current_user.searches
end
def destroy
#search = Search.find(params[:id])
#search.destroy
flash[:success] = "Search deleted"
redirect_to search_path
end
This is my view show:
<% #searches.each do |search| %>
<%= search.title %>
<%= search.description %>
<%= button_to "delete", search, method: :destroy %>
My routes.rb:
get 'search' => 'searches#show'
resources :searches
And I also included <%= javascript_include_tag 'application' %> in the application.html.erb as well as //= require jquery and //= require jquery_ujs in the application.js file.
So I really can't find my mistake. Can someone help me?
In your view file, the code for the button should look like:
<%= button_to "delete", search, method: :delete %>
Note the method is :delete, not :destroy. It's a little confusing, because 'delete' is the REST verb, but 'destroy' is the controller action name.
have you tried:
<%= button_to "Delete", { action: "delete", id: search.id },
method: :delete %>
in you view. Also it appears you are redirecting to search_path but I am guessing you want searches_path.
I got it! In my router I wrote get 'search' => 'searches#show' and somehow my controller was confused with the search_path. Since I renamed it to get 'mysearches' => 'searches#show' and mysearches_path it works perfectly

Rails HTML requests :Post but does a :Get

I have some code for attending/withdrawing from a competition:
<% if #competition.users.exclude?(#user) %>
<%= link_to 'Attend Competition', attend_competition_path(#competition.id), :method => :post %>
<% else %>
<%= link_to 'Withdraw', withdraw_competition_path(#competition.id), :method => :post %>
<% end %>
When I click on the action I go to an error page:
No route matches [GET] "/competitions/1/withdraw"
Why isn't it doing a POST request? How do I fix this?
Not sure if it effects it, but my current js is
//= require jquery
//= require bootstrap
//= require turbolinks
//= require_tree .
thanks

<%= posts_delete_path %> dont work

I'm programming a website with a friend, and I'm getting one error with my code. In the computer of my friend, he have the same code and don't have any error.
I get the following error:
We're sorry, but something went wrong.
Well, we're newbie in Rails and I get this error when I try to load the posts page. We think the error is on deleting a post, because if we comment the line of "posts_delete_path", everything works. For delete a post, we are using:
show.hmtl.erb:
<% #hashtag.posts.each do |p| %>
<li>Posted by: <%= p.user.name %></li>
<li>Content:</li>
<li><%= p.content %></li>
<li><a href="<%= posts_delete_path %>/<%= p.id %>" >Delete</a></li>
<% end %>
routes:
match '/signout', to: 'sessions#destroy'
match 'posts/delete/:id', to: 'posts#destroy'
resources :posts, :only => [:create, :show]
posts controller:
def destroy
#post = Post.find(params[:id])
if current_user.id == #post.user_id
#post.destroy
end
end
---- edit ----
rake routes:
posts GET /posts(.:format) posts#index
POST /posts(.:format) posts#create
new_post GET /posts/new(.:format) posts#new
edit_post GET /posts/:id/edit(.:format) posts#edit
post GET /posts/:id(.:format) posts#show
PUT /posts/:id(.:format) posts#update
DELETE /posts/:id(.:format) posts#destroy
We know that's the newbie way to delete a post, but we don't find any better solution. (If you want suggest something, we will be glad too).
<%= link_to "Delete", p, method: :delete %>
and modify the routes.rb with
resources :posts
You should use the link_to notation like this:
<%= link_to "Delete", p, method: :delete %>
Also, you should try to stop users from even seeing the delete button in the view, something like:
<% if current_user == p.user %>
<%= link_to "Delete", p, method: :delete %>
<% end %>
This will only show the delete link only to the owner of the post.
Also like Ganesh said , turn this:
match 'posts/delete/:id', to: 'posts#destroy'
resources :posts, :only => [:create, :show]
to:
resources :posts, :only => [:create, :show, :destroy]
Checkout the routing system in the rails guides: http://guides.rubyonrails.org/routing.html, and see which of the routes you will need.
looks like ur link is fine, but sounds like you did not include your js, thats why it is redirecting you to the show page when you click delete.
<%= link_to 'Destroy', product, :confirm => 'Are you sure?', :method => :delete %>
1. Check your /assets/application.js for //= require jquery and
//= require jquery_ujs
Add in application.js this code
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
2. Check your /layouts/application.html.erb for <%= javascript_include_tag "application"%>
<head>
<title>My awesome app</title>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application"%>
<%= csrf_meta_tag %>
</head>
Thanks for everyone who tried help me. Now I solved my problem, but by other way.
What I do is:
In view:
<% if current_user.id == p.user_id %>
<%= button_to "Delete", { :controller => :posts, :action => 'destroy', :id => p.id }, :method => :delete %>
<% end %>
In controller:
def destroy
#post = Post.find(params[:id])
#if current_user.id == #post.user_id
#post.destroy
end
end
In routes:
resources :posts
Thanks guys!

Resources