Question

So I've seen that other people have been confused me about this, and I have read other answers but I'm still confused.

How is information stored and parsed into the params hash during a delete request? I understand how it works in regards to submitting information to it. i.e. when a Put, Post or Get request is issued, I understand that the info is passed via params hash to respective controller action.

However, based on the code below in the user partial (_user.html.erb) :

<li>
    <%= gravatar_for user, size: 52 %>
    <%= link_to user.name, user %>

    <% if current_user.admin? && !current_user?(user) %>
    <%= link_to "delete", user, method: delete,
                            data: {confirm: "You sure?"} %>
                            <% end %>
</li>

And the code in the DESTROY action that is automatically routed to:

def destroy
  User.find(params[:id]).destroy
  flash[:success] = "User destroyed."
  redirect_to users_url
end

I don't understand how the params hash gets the user id stored in it. I'd understand if it were params[:user][:id] since we are posting the user which has its list of attributes. But, I don't get how the id gets stored DIRECTLY into the params hash. This has been bothering me for a while so please any insight would be appreciated.

Was it helpful?

Solution 2

It's based on rails routing model.

If you used resources :user in config/routes.db it will create the following route (you can view it by running rake routes) :

DELETE users/:id

the symbol :id means that whatever you add after users/ while calling url will be set in params as :id. (in the case, for the DELETE HTTP verb)

OTHER TIPS

It's the way how rails works. If you do a rake routes you will see that you get something like DELETE /users/:id.

This means that the user object that you pass as the parameter gets interpreted as :id. When Rails sees this, it will know that it has to look at the ID of the object passed, by convention all the models do have an ID field.

So Rails reads in the URL you pass into it and then decides what to do with it.

By convention, it will think that what you pass into it is

:controller/:id

So what it probably does is take in the url as a string, and breaks it down according to the / character.

Try this in IRB.

controller, id = "hello/1".split("\/")

And then type in

id

Imagine that this newly set id variable is passed into a params hash like this:

params = {}
params[:id] = id

Now type in

params[:id]

The truth is way more complicated. I was looking through the source to try and find the specific method but there are just way too many things going on. Try checking out this in ActionDispatch

http://api.rubyonrails.org/classes/ActionDispatch/Routing.html

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top