vidur punj
vidur punj

Reputation: 5871

Using parameter[:user_id] ,params[:user_id], params["userid"] in Rails?

While studying a Rails application I saw statements like:

parameter[:user_id]
params[:user_id]
params["userid"]

Can anyone tell me if there any major difference between them? Or, are all fetching parameters only and can I use them interchangeably?

Upvotes: 1

Views: 1172

Answers (3)

Jiří Pospíšil
Jiří Pospíšil

Reputation: 14402

parameter[:user_id]

I don't think this is something official. However there's a parameters method on the current request object. See request.parameters in a controller action.

params[:user_id]

Using the params[:user_id] is the same as calling request.parameters[:user_id]. Also params[:user_id] is the same as params["user_id"]. See HashWithIndifferentAccess.

I am not sure if that's just a typo on your part, but params[:user_id] and params["userid"] are not the same, even with HashWithIndifferentAccess. The _ won't just go away so they can hold different values.

Upvotes: 2

emrahbasman
emrahbasman

Reputation: 2013

params and parameters are the same. They return both GET and POST parameters in a single hash.

There is no such a thing as parameter.

ref: rails api

Upvotes: 0

harald
harald

Reputation: 6126

No, you need to look at the context in which each one is used. params is the normal parameter hash made available to methods in your controllers. It contains the parameters passed in as part of the request as GET or POST params.

So, given the following URL:

http://www.testsite.org/some_resource?user_id=13

The params[:user_id] would contain the value 13.

If the URL instead was:

http://www.testsite.org/some_resource?userid=13

You would need to use params[:userid] to get the value. So it all comes down to the way the URLs are made for the different controllers.

There's a third way, where you can map parts of the URL itself to params in the routes into your application. See config/routes.rb in your application. For instance with the following route:

match '/user/:user_id' => 'users#show'

You could pass in an URL like this:

http://www.testsite.org/user/13

And in your UsersController.show method you could access the user id by using params[:user_id] like normal.

The parameter hash is most likely a local copy of or reference to the params hash in a helper method or something.

Upvotes: 0

Related Questions