我想在不同控制器的各种视图中使用以下部分。有没有办法用一个更通用的变量来代替@person
,它只需调用当前控制器的实例变量,不管它是@person
还是@user
或@company
或其他什么?如何获取当前控制器的实例变量?
<% content_for(:timestamps) do %>
<p>Created: <%= l @person.created_at, :format => :long %>, Last updated: <%= l @person.updated_at, :format => :long %></p>
<% end %>
感谢您的帮助。
这是一个基于Xavier的代码我的助手功能:
def timestamps
content_for(:timestamps) do
current_string = controller.controller_name.singularize
current_object = instance_variable_get("@#{current_string}")
created_at_time = l(current_object.created_at, :format => :long)
updated_at_time = l(current_object.updated_at, :format => :long)
text = "Created: #{created_at_time}, Last updated: #{updated_at_time}"
content_tag(:p, text)
end
end
这很好,非常感谢!我将代码移入'application_helper.rb'中的一个辅助函数中,并将其发布到上面。我将如何检查错误或nils在这里?不知道我的语法是否也很好。 – Tintin81
@ Tintin81 - 在使用它之前,请确保'current_object'不是零。这是为了防止这个助手从'user_index'被调用,并且没有特定的'user'可以使用。这就是我所能想象的错误......很高兴我能帮上忙! –