Asarluhi
Asarluhi

Reputation: 1290

form_for and form_tag parameters for custom action

I would like to use a drop action in the friendships controller to drop requests of friendship, and I am struggling to understand how to create a working form and working routes.

I added the following route in config/routes.rb

resources :friendships, only: [:create, :destroy] do
  member do
    post :drop
  end
end

This would generate the named route drop_friendship_path(id).
My question is now how to create a working form, that is what parameters am I necessarily required to use with form_for or form_tag.

Since in view I would iterate on @users requesting a friendship, I would not know the id of the request to delete, so I cannot use the above named route. Which one of the following is correct?

<%= form_for(current_user.friendship_request.find_by(requester_id: user.id), url: { action: drop }) %>

<%= form_tag({controller: "friendships_controller", action: "drop"}) do %>

I struggled to find documentation on parameters to use with form_for and form_tag. The api documentation says that the :url argument for form_for may be represented in the same way as values passed to url_for or link_to. So for example you may use a named route directly. Documentation on url_for or link_to however does not add anything else.

I found only examples, not an exhaustive documentation, in the form helpers section of guides.rubyonrails.org for form_for and form_tag, so I realized that url for form_for can have a hash of subparameters (however only action is reported) , and that the controller and action parameters can be passed to form_tag.

What is the complete list of parameters for the url hash in the form_for helper?
What is the relative list of parameters for the form_tag helper?
Which ones are required in my form?

If, instead of specifying controller and action, I used inside form_for or form_tag:

url: drop_friendship_path(@friendship_request) 

and defined @friendship_request in the drop action, would that work?

Upvotes: 0

Views: 601

Answers (1)

chumakoff
chumakoff

Reputation: 7034

A better way is to use button_to or link_to helpers for your purpose. button_to generates a form. link_to generates a link, but can also send post request with {method: :post} option.

Why do you think you can't use the drop_friendship_path(id) helper method? You can:

<% request_id = current_user.friendship_request.find_by(requester_id: user.id) %>

<%= button_to "Drop", drop_friendship_path(request_id) %>
<!-- or -->
<%= link_to "Drop", drop_friendship_path(request_id), method: :post %>

Why don't you use the existing destroy action to delete friendships instead of drop ?

And also, sending a separate query for each user to get a friendship record is not a good thing. You should think of how you can avoid this. There are many solutions, but it is not the subject of the question.

Upvotes: 2

Related Questions