rails 中的全局可访问变量 [英] Globally accessible variable in rails

查看:50
本文介绍了rails 中的全局可访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个可供整个应用程序全局访问的变量.用户将填写单个输入字段表单.然后它将被保存到数据库中,并且该变量可以在任何地方访问.所以这是我到目前为止所做的.

I want a variable that is globally accessible to the whole app. The user will fill a single input field form. It will be then saved into the database and that variable will be accessible anywhere. So here is what I have done so far.

    class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :save_page

  def save_page
    @page_name = params[:page_name ]
    test_page_name = PageName.new
    test_page_name.name = @page_name
    if test_page_name.save
      redirect_to(controller: 'template',action: 'templates')
    end
  end

end

表单提交给 ApplicaitonController 中的 save_page 方法,保存后被重定向.因为这种方法会在成功保存到数据库的情况下重定向,所以给我带来了问题.我该如何解决这个问题?

The form is submitted to save_page method in ApplicaitonController and after being saved it is redirected. Because this method will redirect in case of successfully saved into database, it is giving me problem. How can I fix this?

我也试过这样但没有运气

I also tried like this but no luck

    class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  before_action :page_name

  def save_page
    @page_name = params[:page_name ]
    test_page_name = PageName.new
    test_page_name.name = @page_name
    if test_page_name.save
      redirect_to(controller: 'template',action: 'templates')
    end
  end

  def page_name
    @user_page_name = @page_name
  end

end

但是当我试图在视图中打印 @user_page_name 的值时,我什么也没得到.

but when I tried to print the value of @user_page_name in the view I got nothing.

推荐答案

class ApplicationController < ActionController::Base

# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.

protect_from_forgery with: :exception

before_action :page_name

def param_page

 @page_name=params[:page_name]

end

def save_page

 param_page

 test_page_name = PageName.new

 test_page_name.name = @page_name

 if test_page_name.save

   redirect_to(controller: 'template',action: 'templates')

 end

end

 def page_name

  param_page

  @user_page_name = @page_name

 end

end

这篇关于rails 中的全局可访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆