22

我想要一个链接来更新资源,而不使用 HTML 表单。

路线:

resources :users do
  resources :friends
end    

耙路线:

 user_friend GET /users/:user_id/friends/:id(.:format){:action=>"show", :controller=>"friends"}
             PUT /users/:user_id/friends/:id(.:format){:action=>"update", :controller=>"friends"}

我想通过一个简单的链接使用 put 来更新朋友,如下所示:

<%= link_to "Add as friend", user_friend_path(current_user, :method=>'put') %>

但是当我单击链接时,它会尝试进入显示操作。

这样做的正确方法是什么?

4

2 回答 2

38
link_to "Add as friend", user_friend_path(current_user, @friend), :method=> :put

将插入一个将属性“data-method”设置为“put”的链接,该链接又将被 rails javascript 拾取并在幕后变成一个表单......我想这就是你想要的。

您应该考虑使用 :post,因为您似乎是在两个用户之间创建一个新链接,而不是更新它。

于 2011-01-20T20:09:25.107 回答
1

问题是您将方法指定为 URL 查询参数,而不是作为link_to方法的选项。

这是您实现所需目标的一种方法:

<%= 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' %>

link_to使用帮助器更新模型属性的另一种方法是传递查询参数。例如:

<%= 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' %>

这将提出这样的请求:

Started PATCH "/friend_requests/123?friend_request%5Bstatus%5D=accepted"
Processing by FriendRequestsController#update as 
  Parameters: {"friend_request"=>{"status"=>"accepted"}, "id"=>"123"}

您可以在这样的控制器操作中处理:

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
于 2020-05-22T18:56:25.647 回答