为什么自我在这里似乎是零?

时间:2016-01-19 00:05:02

标签: ruby-on-rails ruby ruby-on-rails-4 rails-activerecord ruby-2.0

在模型中,我有以下内容:

after_create :send_to_user
def send_to_user
    puts "self before if is #{self.inspect}"
    if self.non_user_email
        puts "self after if is #{@self.inspect}"
        @document = self.document
        @email = self.non_user_email
        ...
    end
end

出于某种原因,第一个puts知道self是什么,但第二个puts显示为nil:

self before if is 
#<Transaction id: 6, document_id: 2, buyer_id: nil, amount: nil, created_at: "2016-01-18 23:58:43", updated_at: "2016-01-18 23:58:43", author_id: 1, non_user_email: "pghrpg@gmail.com">
self after if is nil

这怎么可能?

1 个答案:

答案 0 :(得分:3)

当你应该发送puts时,你给第二个@self一个名为self的实例变量。实例变量(以@开头的变量)默认为nil。你只需要在自我面前摆脱额外的@,就像这样:

puts "self after if is #{self.inspect}"