gpt4 book ai didi

ruby-on-rails - 如何根据 Controller 名称查询模型

转载 作者:太空宇宙 更新时间:2023-11-03 18:02:39 29 4
gpt4 key购买 nike

我一直在重构我的模型和 Controller ,以努力消除代码重复,到目前为止,它似乎都是桃子般的奶油状。目前我有一些我的两个 Controller 通用的代码,如下所示:

def process_filters
# Filter hash we're going to pass to the model
filter_to_use = {}

# To process filters, we first query the model to find out what filters
# we should be looking for, as the model knows what we can filter.
Iso.available_filters.each do |filter|
# We should have our array with our filter listing.
# Check the purchase order model for a description
filter_name = filter[0][:filter_name]

# Filters are stored in a session variable, this way filters survive
# page reloads, etc. First thing we do, is set the session if new filters
# have been set for the filter.
session_name = session_filter_name( filter_name )
if params[session_name]
if params[session_name] == 'All'
session[session_name] = nil
else
session[session_name] = params[session_name]
filter_to_use[filter_name] = params[session_name]
end
elsif session[session_name]
# If params aren't read, we still need to filter based off the users
# session
filter_to_use[filter_name] = session[session_name]
end
end

# Just using this variable for now until I can refactor the helper code
# so that this is passed in.
@current_filter_values = filter_to_use

filter_to_use[:page] = @current_page

@isos = Iso.find_filtered( filter_to_use )

if @isos.out_of_bounds?
filter_to_use[:page] = session[:previous_page] = @current_page = 1
@isos = Iso.find_filtered( filter_to_use )
end
end

现在这段代码与另一个 Controller 中的代码完全相同,除了模型引用(在本例中为 Iso)。有什么办法可以使该模型引用动态化吗?

基本上,我想将 Iso 引用(包括 @iso 变量)替换为基于 controller.controller_name 或类似内容的内容。

最佳答案

您可以将此代码移动到模块中,将此模块混合到您需要的所有 Controller 中,并使用模块内的 self.class 变量来确定具体的 Controller 名称。使用此名称,您可以使用标准字符串函数(例如大写)和 Kernel.const_get 函数通过名称获取类。

关于ruby-on-rails - 如何根据 Controller 名称查询模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/190054/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com