ruby-on-rails - 如何在 Ruby on Rails 中声明一个全局变量?

标签 ruby-on-rails ruby

如何在 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=1Doe=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/

相关文章:

ruby-on-rails - Rails - 如何保护外键并仍然允许关联选择

ruby-on-rails - 当我在 Rails 中收到 PG::ForeignKeyViolation 错误时,如何显示一个闪现通知消息

ruby-on-rails - 在 rails 中缓存 http 调用结果

mysql - Rails - MySQL 错误 "Out of range value",即使范围应该没问题?

ruby - 用Ruby中的哈希值总结对象区域

ruby-on-rails - 地理编码器 gem 的 country_code 列表

ruby-on-rails - 你可以用ruby重新定义一个类吗?或者这只是在 irb

ruby - ruby 的 rand 方法应该接受 Range 对象吗?

ruby-on-rails - rails 5.x : How can I add a route at runtime without overwriting original routes table?

ruby-on-rails - 在 Rails 中,使用 check_box_tag,如何在提交查询后保持选中复选框?