link_to update (without form) link_to update (without form) ruby-on-rails ruby-on-rails

link_to update (without form)


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_pathend