首页 > 解决方案 > Rails 4:如何从配置控制器添加动态全局变量

问题描述

我希望添加一个应用程序级别的全局横幅,由我们 CMS 的输入数据填充。我们在配置控制器中添加主页设置,但我希望可以从每个页面访问该数据。它只能在我们的主页上运行,并且每个其他页面都会给出 Nil:NilClass 错误。我是一名 python 开发人员,这个概念让我在 Rails 中感到困惑——在 python 中,你可以只“从 app.models 导入模型”,这样就可以访问了——我将如何在 rails 中做到这一点?抱歉,如果这很难理解,我不太擅长 ruby​​ on rails。

我希望从配置控制器访问“ticker_copy”

配置控制器:

def edit
    @path = admin_edit_config_path
  end

  def update
    @path = admin_edit_config_path
    if @config.update(config_params)
      redirect_to admin_edit_config_path, notice: 'Settings successfully updated.'
    else
      render :edit, notice: 'Settings could not be updated.'
    end
  end

  private
    def set_config
      @config = Config.first
      authorize @config
    end

    def set_alternate_message_options
      @alternate_message_options = Config::ALTERNATE_MESSAGES.map{|am| [ am, am ]}
    end
    def set_first_alternate_message_options
      @first_alternate_message_options = Config::FIRST_ALTERNATE_MESSAGES.map{|am| [ am, am ]}
    end

    def config_params
      params.require(:config).permit(
        :show_default_hours,
        :custom_hours,
        :show_ticker,
        :ticker_copy,
        :ticker_link,
        :ticker_link_copy,
        :show_default_message,
        :first_alternate_message,
        :alternate_message,
        :show_default_link,
        :left_custom_link_title,
        :left_custom_link_url,
        :custom_link_title,
        :custom_link_url,
        :tour_hours,
        :home_page_video,
        :remove_home_page_video
      )
    end

应用程序控制器:我正在尝试做这样的事情

def set_ticker
    @ticker_copy = config.find(params[:ticker_copy])
end

楷模:

field :ticker_copy, type: String

HTML 部分

<h1 id="ticker">
  <%= @config.ticker_copy %>
</h1>

我正在使用 Rails 4.2.6

标签: ruby-on-railsruby

解决方案


你的set_ticker方法看起来不正确。Config.find通过主键查找记录。我认为你想要做的是

def set_ticker
    @ticker_copy = Config.find_by(ticker_copy: params[:ticker_copy])
end

推荐阅读