简体   繁体   中英

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" ?

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, ie,

{ "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!

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM