Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3.2, how to write route for HTTP verb put, and use it in link_to?

I am trying to write two links for reject& approve actions, but, I don't know how to write the correct route,

my route.rb

put 'approve_class_room/:id(.:format)', :to => 'class_room_member_ships#approve'
put 'reject_class_room/:id(.:format)', :to => 'class_room_member_ships#reject'

but, in rake routes, I get:

PUT    /approve_class_room/:id(.:format) class_room_member_ships#approve
PUT    /reject_class_room/:id(.:format)  class_room_member_ships#reject

so, what would be the correct link_to path ?

my link is

= link_to 'approve', approve_class_room_path

it wont' work, I get:

undefined local variable or method `approve_class_room_path'

p.s: I am trying to have the link_to works using AJAX, to do the approve in the same page, AM I on the right way ? what would be the link_to path ?

Any idea please ?

like image 632
simo Avatar asked May 31 '12 18:05

simo


2 Answers

First, to clear the error you need to use named routes:

put 'approve_class_room/:id(.:format)', :to => 'class_room_member_ships#approve',
                                        :as => :approve_class_room
put 'reject_class_room/:id(.:format)', :to => 'class_room_member_ships#reject',
                                       :as => :reject_class_room

Then, to perform a PUT request, you need to include the :method option in your link_to call:

link_to 'approve', approve_class_room_path, :method => :put
link_to 'reject', reject_class_room_path, :method => :put

If you are getting a 404 that results in a GET request instead of a PUT request, it's because the :method => :put option relied on JavaScript. You'll need to make sure jquery-rails is properly integrated in your app.

like image 129
Matt Huggins Avatar answered Sep 29 '22 16:09

Matt Huggins


This may not clear that error, but since the request is a put, you need to specify that in the link_to:

= link_to 'approve', approve_class_room_path, :method => :put

For the route, I think adding this would make the error go away:

put 'approve_class_room/:id(.:format)', :to => 'class_room_member_ships#approve', :as => :approve_class_room
like image 42
Bill Turner Avatar answered Sep 29 '22 18:09

Bill Turner