Ruby on Rails Tutorial Confused about How Hash Pairs Work

So, I saw that other people embarrassed me, and I read other answers, but I'm still confused.

How is information stored in the params hash stored and parsed during a delete request? I understand how this works in relation to providing him with information. that is, when a Put, Post or Get request is issued, I understand that the information is transmitted through the hash of the params hash to the corresponding controller action.

However, based on the code below in 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 action is DESTROY, which automatically redirects to:

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

I do not understand how the params hash gets the user id stored in it. I would understand if these were params [: user] [: id], since we are sending a user who has his own list of attributes. But I do not understand how the identifier is stored DIRECTLY in params hashes. It bothered me for a while, so please, any understanding will be appreciated.

+4
source share
3 answers

It is based on a rail routing model.

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

DELETE users /: id

symbol: id means that everything that you add after users / when calling url will be set in parameters as: id. (in case for DELETE HTTP verb)

+2
source

How does the rail work. If you do rake routes , you will see that you got something like DELETE /users/:id .

This means that the user object you pass as a parameter is interpreted as :id . When Rails sees this, he will know that he should look at the identifier of the transferred object, by convention, all models have an identifier field.

+3
source

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

By convention, he will think that what you pass on to him

:controller/:id

So probably do it in url as a string and break it according to the / character.

Try this on IRB.

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

And then enter

id

Suppose this newly set id variable is passed to the params hash as follows:

 params = {} params[:id] = id 

Now enter

params[:id]

The truth is much more complicated. I scanned the source to try and find a specific method, but there are too many things that happen. Try checking it out in ActionDispatch

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

Good luck

+2
source

Source: https://habr.com/ru/post/1494808/


All Articles