Global variable in Rails

后端 未结 4 2135
一生所求
一生所求 2021-02-14 10:58

I have a feedback form in my Rails application. The feedback form requires initializing of the @support variable, and it should be visible on every page. The initialization is v

相关标签:
4条回答
  • 2021-02-14 11:29

    Rather than a global variable, you probably want to put something in the ApplicationController.

    Either:

    before_filter initialize_support
    
    def initialize_support
          @support = Support.new(:id => 1)
    end
    

    Or:

    helper_method support_form
    
    def support_form
          @support_form ||= Support.new(:id => 1)
    end
    
    0 讨论(0)
  • 2021-02-14 11:36

    It sounds like what you really want is to store the data in the user's session, right? For more details, see http://www.ozmox.com/2009/10/13/rails-sessions/.

    0 讨论(0)
  • 2021-02-14 11:43

    you can use a helper method (in the application controller) to initialize the support variable . Something like this :

    class ApplicationController < ..
       ...
       helper_method :my_var
    
       def my_var
          @support = Support.new(:id => 1)
       end
       ...
    
     end
    
    0 讨论(0)
  • 2021-02-14 11:45

    A global variable starts with the dollard sign '$' like :

    $support = Support.new(:id => 1)
    

    However, global variables is bad :-) You should read this post by "Simone Carletti".

    0 讨论(0)
提交回复
热议问题