简体   繁体   English

rails 控制台和 put 中的不同结果

[英]Different result in rails console and in puts

When I use puts(@participantt = Participant.where(id: 1)) then in the console I get当我使用puts(@participantt = Participant.where(id: 1))然后在控制台中我得到

  Participant Load (0.3ms)  SELECT "participants".* FROM "participants" WHERE "participants"."id" = $1  [["id", 1]]
  ↳ app/controllers/interviews_controller.rb:119:in `puts'
#<Participant:0x000000000c778bf0>

But if I type @participantt = Participant.where(id: 1) in rails console then I get但是,如果我在 rails 控制台中输入@participantt = Participant.where(id: 1) ,那么我会得到

  Participant Load (0.7ms)  SELECT "participants".* FROM "participants" WHERE "participants"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Participant id: 1, name: "Ram", email: "Ram@g.com", created_at: "2020-05-08 08:19:00", updated_at: "2020-05-08 08:19:00">]>

Why is this so?为什么会这样?

puts calls to_s on before printing result of expression(which will be an object) passed to it.在打印传递给它的表达式(这puts是一个对象)的结果之前调用to_s It generally prints class name with it's object id.它通常打印 class 名称及其 object id。

Here, result of @participant = Participant.where(id: 1) is the Participant with id and get stored in instance variable @participant这里, @participant = Participant.where(id: 1)的结果是具有 id 的参与者,并存储在实例变量@participant

Passing @participant to puts will first call @participant.to_s before printing it.@participant传递给puts将在打印之前首先调用@participant.to_s

In case of just @participant = Participant.where(id: 1) , the console shows the result which is typical REPL utility does.如果只是@participant = Participant.where(id: 1) ,控制台会显示典型的 REPL 实用程序的结果。 And if you do puts @participant there after then you will again get same as what you get with puts in you question.而且,如果您确实puts @participant那里,那么您将再次获得与puts问题相同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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