如何在 Ruby on Rails 中声明全局变量?
我的示例代码:
在我的 controller#application.rb
中:
def user_clicked()
@current_userid = params[:user_id]
end
在我的layout#application.html.haml
我有这个链接的侧边栏:
= link_to "John", user_clicked_path(:user_id => 1)
= link_to "Doe", user_clicked_path(:user_id => 2)
= link_to "View clicked user", view_user_path
在我的views#view_user.html.haml
中:
%h2 @current_userid
我想声明一个全局变量,它可以修改我的 Controller 并在任何地方使用它,比如 Controller 、 View 等。以上只是一个示例场景。如果我单击 John 或 Doe 链接,它会向 Controller 发送一个 user_id
,当我单击“View clicked user”链接时,它会显示上次单击的链接。它是 John=1
或 Doe=2
。
当然,如果我先点击“View clicked user”链接,它会显示nil
。
最佳答案
在 Ruby 中,全局变量是通过在标识符前加上 $
$foo = 'bar'
您很少看到它用于 a number of reasons .这并不是您真正要找的东西。
在 Ruby 中,实例变量使用 @
声明:
class DemoController
def index
@some_variable = "dlroW olleH"
@some_variable = backwards
end
private
def backwards
@some_variable.reverse
end
end
Rails 自动将 Controller 的实例变量传递给 View 上下文。
# /app/views/demos/index.html.haml
%h1= @some_variable
猜猜它输出什么,我会给你一个 cookie。
在您的示例中,@global_variable
为 nil,因为未调用 controller#sample_1
- 请求将通过 controller#sample_2
。
def sample_2
@global_variable = "Hello World"
end
关于ruby-on-rails - 如何在 Ruby on Rails 中声明一个全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30321752/