撬命令 - 自我,保存

时间:2015-05-05 06:18:09

标签: save self pry

我正在进行一项练习,要求我使用pry来cd我最初在rails控制台中创建的帖子,然后使用self并保存!更改此帖子的标题。我没有看到在pry help命令下列出的任何一个,所以我被卡住了。

这是显示:

[13] pry(#<Post>):1> Post.first                                                                                                                                                               
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts"   ORDER BY "posts"."id" ASC LIMIT 1                                                                                                       
=> #<Post id: 1, title: "First Post", body: "This is the first post in our system", created_at: "2015-05-05 03:55:22", updated_at: "2015-05-05 03:55:22">

2 个答案:

答案 0 :(得分:2)

Pry是Ruby的IRB shell的增强替代品。这意味着您还可以在Pry会话中运行Ruby。在此上下文中,self引用Ruby中的关键字,save!引用Ruby方法。

要更改帖子的标题并保存,它看起来像这样:

$ rails c
Loading development environment (Rails 4.1.6)
[1] pry(main)> Post.first
  Post Load (0.2ms)  SELECT  "posts".* FROM "posts"   ORDER BY "posts"."id"       ASC LIMIT 1
=> #<Post id: 1, title: "My first post", body: "This is the first post!",   created_at: "2015-05-14 20:47:49", updated_at: "2015-05-14 21:42:02">
[2] pry(main)> cd Post.first
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts"   ORDER BY "posts"."id" ASC LIMIT 1
[3] pry(#<Post>):1> self.update title: "My new title"
   (0.1ms)  begin transaction
  SQL (1.3ms)  UPDATE "posts" SET "title" = ?, "updated_at" = ? WHERE   "posts"."id" = 1  [["title", "My new title"], ["updated_at", "2015-05-14   21:42:36.731568"]]
   (2.9ms)  commit transaction
=> true
[4] pry(#<Post>):1> Post.first.save!
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts"   ORDER BY "posts"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
   (0.1ms)  commit transaction
=> true
[5] pry(#<Post>):1> Post.first
  Post Load (0.2ms)  SELECT  "posts".* FROM "posts"   ORDER BY "posts"."id" ASC LIMIT 1
=> #<Post id: 1, title: "My new title", body: "This is the first post!",     created_at: "2015-05-14 20:47:49", updated_at: "2015-05-14 21:42:36">
[6] pry(#<Post>):1> 

答案 1 :(得分:0)

我不确定如何使用“保存!”在这种情况下,因为字符串没有该方法。我设法改变了标题:

self.update:title =&gt; “改变帖子”