【问题标题】:Why does self appear to be nil here?为什么 self 在这里看起来为零?
【发布时间】:2016-01-19 00:05:01
【问题描述】:

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

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

这怎么可能?

【问题讨论】:

  • 在第二个puts 语句中,您使用的是@self 而不是self。投票以“错别字”结束。

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


【解决方案1】:

你给第二个puts一个名为@self的实例变量,而你应该只发送它self。实例变量(以@ 开头的变量)默认为nil。你只需要去掉 self 前面的那个多余的@,就像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 2020-02-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多