ruby-on-rails - 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
解决方案
你的set_ticker
方法看起来不正确。Config.find
通过主键查找记录。我认为你想要做的是
def set_ticker
@ticker_copy = Config.find_by(ticker_copy: params[:ticker_copy])
end
推荐阅读
- php - 使用 PHP/Laravel 从 HTTP 响应而不是路径中提取二进制 zip 文件
- less - 如何编译更少以将@import 删除并合二为一?
- scala - 通过scala中的反射检查两种类型是否等价
- sharepoint - 如何防止 SharePoint 2016 人员选取器显示同一用户的重复帐户?
- sql - 带 PIVOT 的 CROSSTAB
- vbscript - 通过文件夹中的文件夹递归运行的 VBS 问题
- python-3.x - 将数据帧解析为 SQL 表的函数
- python - 如何在 Python 中读取文本并标记其中的每个单词
- kotlin - RecyclerView 中的应用程序崩溃 - 使用 Kotlin 的 DataBindingUtil.inflate()
- google-analytics - Google Analytics:事件已收集但未在 GA 中显示