tardis
tardis

Reputation: 243

Ruby on Rails Tutorial chapter 7.21, params[:user]

I'm a beginner of ROR, I read chapter 7.21.

class UsersController < ApplicationController
  .
  .
  .
  def create
    @user = User.new(params[:user])    # Not the final implementation!
    if @user.save
      # Handle a successful save.
    else
      render 'new'
    end
  end
end 

When submit a form to create a new user, params[:user] get the information from the form, and get a hash in debug info:

"user" => { "name" => "Foo Bar",
            "email" => "foo@invalid",
            "password" => "[FILTERED]",
            "password_confirmation" => "[FILTERED]"
          }

I konw params is a hash of hash, but don't know the meaning of params[:user]. What's :user mean? The :user represent the User model or just a variable name ? What is the relationship of :user and "user" ?

Upvotes: 0

Views: 40

Answers (2)

sagunshre
sagunshre

Reputation: 1

read this Rails params explained? here you will find explanation of what is params in rails.

:user is Symbol and "user" is string In Ruby, a string is mutable, whereas a symbol is immutable. That means that only one copy of a symbol needs to be created. Thus, if you have

x = :my_str

y = :my_str

:my_str will only be created once, and x and y point to the same area of memory. On the other hand, if you have

x = "my_str"

y = "my_str"

a string containing my_str will be created twice, and x and y will point to different instances.

As a result, symbols are often used as the equivalent to enums in Ruby, as well as keys to a dictionary (hash).

Upvotes: 0

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

The answer is in your question, you have this hash

"user" => { "name" => "Foo Bar",
            "email" => "foo@invalid",
            "password" => "[FILTERED]",
            "password_confirmation" => "[FILTERED]"
          }

Here, "user" is the key, so to access the values of this key, we write params["user"] or params[:user], which will give in return all the values, here the value is a hash, i.e.,

{ "name" => "Foo Bar",
  "email" => "foo@invalid",
  "password" => "[FILTERED]",
  "password_confirmation" => "[FILTERED]"
}

So when you are writing @user = User.new(params[:user]), you are actually passing the value of the key "user", like this

@user = User.new({ "name" => "Foo Bar",
                   "email" => "foo@invalid",
                   "password" => "[FILTERED]",
                   "password_confirmation" => "[FILTERED]"
                })

And yes, "user" is singular, like User model

Hope this helps!

Upvotes: 1

Related Questions