在我的记录索引中,我希望通过参数帮助器插入一个图标,其名称在模型中计算,使用参数。 检索参数实际上不起作用。
在BusinessRules索引表中,我指定了一个图像标记:
<td><%= image_tag(business_rule.index_audit_tag, :alt => "Quality hit") %>
我从模型中的公共函数中提取:
### display audit tag filename
def index_audit_tag
ratio = (1-self.bad_records / (self.all_records+1)) * 100
image_file = case ratio
when 0..60 then "red.png"
when 60..90 then "yellow-png"
# when red_threshold..yellow_threshold then red_image
# when yellow_threshold..green_threshold then yellow_image
else "green.png"
end
return image_file
end
在硬编码时它工作正常,但我想使用参数_helper提供的red_threshold等参数:
def red_threshold
list_id = ParametersList.where("code=?", 'LIST_OF_DISPLAY_PARAMETERS').take!
@myparam = Parameter.where("parameters_list_id=? AND name=? AND ? BETWEEN active_from AND active_to", list_id, 'Tag 1-Green light', Time.now ).take!
@myparam.param_value.to_i
end
如果我尝试使用这些参数,我会收到错误:
undefined local variable or method `red_threshold'
我该怎么做?
答案 0 :(得分:1)
您无法在模型中调用辅助方法。助手位于MVC的视图层,模型位于模型层。要解决此问题,您需要将逻辑的两半放在同一层中。
如果您想在模型图层中保留index_audit_tag
:
在Parameter
模型中:
类参数
def self.red_threshold
list_id = ParametersList.where("code=?", 'LIST_OF_DISPLAY_PARAMETERS').take!
myparam = Parameter.where("parameters_list_id=? AND name=? AND ? BETWEEN active_from AND active_to", list_id, 'Tag 1-Green light', Time.now ).take!
myparam.param_value.to_i
end
end
(注意:你可以改进这个来做一个查询,但我不清楚你的数据模型,所以我没有尝试。)
在BusinessRule
模型中:
def index_audit_tag
ratio = (1-self.bad_records / (self.all_records+1)) * 100
image_file = case ratio
when 0..60 then "red.png"
when 60..90 then "yellow-png"
when Parameter.red_threshold..Parameter.yellow_threshold then red_image
when Parameter.yellow_threshold..Parameter.green_threshold then yellow_image
else "green.png"
end
return image_file
end
如果您想将图标逻辑放在视图层中:
许多人会争辩说选择正确图标的逻辑不属于模型。所以另一种方法(也可能是我会这样做)是从模型中删除index_audit_tag
,并将其放在帮助器中:
def index_audit_tag_for(business_rule)
ratio = (1-business_rule.bad_records / (business_rule.all_records+1)) * 100
image_file = case ratio
when 0..60 then "red.png"
when 60..90 then "yellow-png"
when red_threshold..yellow_threshold then red_image
when yellow_threshold..green_threshold then yellow_image
else "green.png"
end
return image_file
end
然后找到同样在视图中的*_threshold
方法也没有问题。