链接到更新 (不含表格)

问题描述 投票:21回答:1

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

路径。

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"}

我想用一个简单的链接来更新一个朋友,就像这样。

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

但当我点击链接时,它试图进入显示操作。

请问正确的做法是什么?

ruby-on-rails routes link-to put
1个回答
36
投票
link_to "Add as friend", user_friend_path(current_user, @friend), :method=> :put

将插入一个属性为'data-method'的链接,设置为'put',这将被rails的javascript识别并在后台变成一个表单...... 我想这就是你想要的。

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


0
投票

问题是你将方法指定为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
© www.soinside.com 2019 - 2024. All rights reserved.