在 rails 中创建后打印对象属性
Print Object attributes after creation in rails
我是 rails 的新手,我想在控制台中打印最后创建的 Document
记录的名称。为此我在模型文件中使用,之后?创建回调。
无论如何,在我 运行 创建程序后,我无法在控制台中显示名称。如何才能显示最后创建的 Document
类型记录的名称?
class Document < ApplicationRecord
belongs_to :storage
after_create :my_function
def my_function
puts Document.name
end
end
当您使用 Document
时,您引用的是 class,而不是新创建的实例。相反:
def my_function
puts name
end
为了更好的理解,您也可以拨打:
def my_function
puts self.name
end
以便您看到您正在对当前实例调用此 name
方法。虽然这不是惯用语。
如果要打印文档最后创建的记录,
你应该做
puts Document.last.name
基本上,当您调用 'Document.name' 时,您是在调用 class 文档上的实例方法 #name。您需要在实例上调用它,也就是记录。
如果您想打印出您正在访问的当前文档记录的名称
puts self.name
所有这些都假设您的 Document 模型上有一个 name 属性。
我是 rails 的新手,我想在控制台中打印最后创建的 Document
记录的名称。为此我在模型文件中使用,之后?创建回调。
无论如何,在我 运行 创建程序后,我无法在控制台中显示名称。如何才能显示最后创建的 Document
类型记录的名称?
class Document < ApplicationRecord
belongs_to :storage
after_create :my_function
def my_function
puts Document.name
end
end
当您使用 Document
时,您引用的是 class,而不是新创建的实例。相反:
def my_function
puts name
end
为了更好的理解,您也可以拨打:
def my_function
puts self.name
end
以便您看到您正在对当前实例调用此 name
方法。虽然这不是惯用语。
如果要打印文档最后创建的记录,
你应该做
puts Document.last.name
基本上,当您调用 'Document.name' 时,您是在调用 class 文档上的实例方法 #name。您需要在实例上调用它,也就是记录。
如果您想打印出您正在访问的当前文档记录的名称
puts self.name
所有这些都假设您的 Document 模型上有一个 name 属性。