我试图将应用控制器中设置的变量传递到应用程序布局。
如果我使用以下内容:
如果我使用以下内容:
@var = 'foo'
应用程序布局不知道我在说什么。
如果我使用全局变量
$var = 'foo'
我的应用程序布局可以正常工作。 但是,我的功能测试不起作用:
# application layout
# my var is an AR object
$var.name
# Stock functional test
class HomeControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
end
end
# test:functionals
ActionView::Template::Error: undefined method `name' for nil:NilClass
我希望这个变量在应用程序布局中可用(每个页面都有)。你有什么想法?我是否需要将其作为会话变量?
更新
根据我正在阅读的其他帖子,将它们放在应用程序助手中,然后从布局调用它们被认为是最佳实践吗?
# Application helper
def get_var
Product.first
end
# Application layout
<% @var = get_var %>
<!DOCTYPE html>
<html lang="en">
<head>
...
这种方法在我的浏览器中是可行的,并且测试也通过了。 这是最佳实践吗? 是否有更简单/更好的方法?