Creating user objects
進入 Rails console 來學習有關 User model 的構成,為了避免在資料庫留下資料,要加個參數 --sandbox,當你離開 console 時,所有在 console 建的資料就會消失:
$ rails console --snadbox
Loading development environment in sandbox
Any modifications you make will be rolled back on exit
建立一個新的使用者:
> User.new
=> #<User id: nil, name: nil, email: nil, created_at: nil, updated_at: nil>
如果沒有給值的話,值預設都是 nil。來給個值吧:
> user = User.new(name: "Luffy Wang", email: "[email protected]")
=> #<User id: nil, name: "Luffy Wang", email: "[email protected]", created_at: nil, updated_at: nil>
使用 valid? 方法查看使用者是否有效:
> user.valid?
=> true
目前為止都還沒碰到資料庫,User.new 只是在記憶體內建立一個物件,user.valid? 只是驗證這個物件是否有效,為了要把資料存進資料庫,需要執行 save 方法:
> user.save
(0.1ms) SAVEPOINT active_record_1
SQL (1.3ms) INSERT INTO "users" ("name", "email", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["name", "Luffy Wang"], ["email", "[email protected]"], ["created_at", "2016-03-06 07:31:20.557133"], ["updated_at", "2016-03-06 07:31:20.557133"]]
(0.1ms) RELEASE SAVEPOINT active_record_1
=> true
如果儲存成功會回傳 true 反之 false,不過目前在 console 儲存都會成功,因為還沒有建立驗證的機制。為了參考用,Rails console 會顯示對應 user.save 的 SQL 指令(INSERT INTO "users"...)。
查詢剛剛建立的使用者:
> user
=> #<User id: 1, name: "Luffy Wang", email: "[email protected]", created_at: "2016-03-06 07:31:20", updated_at: "2016-03-06 07:31:20">
還沒儲存前的 id、created_at、updated_at 值都是 nil,儲存後都已更新。
實例化(instances)的 User model 物件,可以用 . 來查詢屬性值:
> user.name
=> "Luffy Wang"
> user.email
=> "[email protected]"
> user.updated_at
=> Sun, 06 Mar 2016 07:31:20 UTC +00:00
剛剛先用 new 建立使用者,然後再用 save 存進資料庫,但也可以使用 create 一次同時執行:
> User.create(name: "Another", email: "[email protected]")
=> #<User id: 2, name: "another", email: "[email protected]", created_at: "2016-03-06 07:46:38", updated_at: "2016-03-06 07:46:38">
create 方法並不會回傳 true 或 false,它是回傳物件本身,如果要指派變數給它也是可以:
> foo = User.create(name: "Foo", email: "[email protected]")
刪除資料則是用 destroy:
> foo.destroy
=> #<User id: 3, name: "Foo", email: "[email protected]", created_at: "2016-03-06 07:49:31", updated_at: "2016-03-06 07:49:31">
destroy 跟 create 一樣是回傳物件本身。不過查詢被刪除的物件會發現,它還是保留在記憶體內:
> foo
=> #<User id: 3, name: "Foo", email: "[email protected]", created_at: "2016-03-06 07:49:31", updated_at: "2016-03-06 07:49:31">