Reputation: 1765
I want a link to update a resource, without using an HTML form.
Routes:
resources :users do
resources :friends
end
Rake routes:
user_friend GET /users/:user_id/friends/:id(.:format){:action=>"show", :controller=>"friends"}
PUT /users/:user_id/friends/:id(.:format){:action=>"update", :controller=>"friends"}
I want to use the put to update a friend by a simple link, something like this:
<%= link_to "Add as friend", user_friend_path(current_user, :method=>'put') %>
But when I click the link, it tries to go into the show action.
What is the right way to do this?
Upvotes: 25
Views: 26816
Reputation: 52268
In rails 7, this worked nicely for me:
<% if page.published? %>
<%= button_to 'Unpublish', page_path(page: { status: "draft" }), { method: :patch, form: { data: { turbo: true } } } %>
<% else %>
<%= button_to 'Publish', page_path(page: { status: "published" }), { method: :patch, form: { data: { turbo: true } } } %>
<% end %>
Note: you may be able to simplify it further by removing form: { data: { turbo: true } }
- I only include that because I had turbo turned off by default across my app, but most people probably won't, so you could remove it.
Upvotes: 0
Reputation: 238667
The problem is that you're specifying the method as a URL query param instead of as an option to the link_to
method.
Here's one way that you can achieve what you're looking for:
<%= link_to "Add as friend", user_friend_path(current_user, friend), method: 'put' %>
# or more simply:
<%= link_to "Add as friend", [current_user, friend], method: 'put' %>
Another way of using the link_to
helper to update model attributes is by passing query params. For example:
<%= link_to "Accept friend request", friend_request_path(friend_request, friend_request: { status: 'accepted' }), method: 'patch' %>
# or more simply:
<%= link_to "Accept friend request", [friend_request, { friend_request: { status: 'accepted' }}], method: 'patch' %>
That would make a request like this:
Started PATCH "/friend_requests/123?friend_request%5Bstatus%5D=accepted"
Processing by FriendRequestsController#update as
Parameters: {"friend_request"=>{"status"=>"accepted"}, "id"=>"123"}
Which you could handle in a controller action like this:
def update
@friend_request = current_user.friend_requests.find(params[:id])
@friend_request.update(params.require(:friend_request).permit(:status))
redirect_to friend_requests_path
end
Upvotes: 4
Reputation: 3804
link_to "Add as friend", user_friend_path(current_user, @friend), :method=> :put
Will insert a link with attribute 'data-method' set to 'put', which will in turn be picked up by the rails javascript and turned into a form behind the scenes... I guess that's what you want.
You should consider using :post, since you are creating a new link between the two users, not updating it, it seems.
Upvotes: 40