开发者

link_to update (without form)

开发者 https://www.devze.com 2023-02-06 08:10 出处:网络
I want a link to update a resource, without using an HTML form. Routes: resources :users do resources :friends

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?


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消