我正在尝试在应用程序控制器中获取变量集以冒泡到应用程序布局.
如果我使用:
@var = 'foo'
Run Code Online (Sandbox Code Playgroud)
...应用程序布局不知道我在说什么
如果我使用全局变量
$var = 'foo'
Run Code Online (Sandbox Code Playgroud)
...应用程序布局有效.但是,我的功能测试不起作用:
# 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
Run Code Online (Sandbox Code Playgroud)
我需要这个var可用于应用程序布局(每页).思考?我需要将其作为会话变量吗?
根据我正在阅读的其他几篇文章,将这些文章放在应用程序助手中,然后从布局中调用它们是最佳做法吗?
# Application helper
def get_var
Product.first
end
# Application layout
<% @var = get_var %>
<!DOCTYPE html>
<html lang="en">
<head>
...
Run Code Online (Sandbox Code Playgroud)
这个a)在我的浏览器中工作,b)通过测试.这是最佳做法吗?有更简单/更好的方法吗?
KMC*_*KMC 21
您是否尝试过before_filter声明变量的方法,以确保每个其他控制器调用它并将变量传递给相应的视图?
class ApplicationController <ActionController :: Base
before_filter:foo_function
def foo_function
@var ="foo"
end
end
如果@var是AR对象而不是字符串,您确定正确定义了模型名称和列名称吗?
| 归档时间: |
|
| 查看次数: |
11219 次 |
| 最近记录: |