我需要在我的application_helper.rb中使用def,它将接受作为变量传递的模型名称。
我有一个导航视图,我试图根据$ current_opportunity的内容访问特定记录
<%# link_to "Lab", lab_path(get_id('Lab')), class: get_labs_class() %>
我试图做的是调用get_id并将'Lab'传递给它。
我的application_helper.rb有
def get_id(model)
model_ids = model.where("opportunity_id = ? ", $current_opportunity)
model_ids = model_ids.first
model_id = model_ids.id
model_id = model_id.to_i
return model_id
end
如果我尝试这样跑,我会
NoMethodError in Prospects#show
Showing C:/Users/cmendla/RubymineProjects/product_development/app/views/shared/_tabs_nav.html.erb where line #61 raised:
undefined method `where' for "Lab":String
Trace of template inclusion: app/views/layouts/application.html.erb
Rails.root: C:/Users/cmendla/RubymineProjects/product_development
Application Trace | Framework Trace | Full Trace
app/helpers/application_helper.rb:25:in `get_id'
app/views/shared/_tabs_nav.html.erb:61:in `_app_views_shared__tabs_nav_html_erb__956794461_83328552'
app/views/layouts/application.html.erb:113:in `_app_views_layouts_application_html_erb___468328524_46368744'
但是,如果我将def更改为
model_ids = Lab.where("opportunity_id = ? ", $current_opportunity)
即硬接线实验室,一切正常。
有没有办法在where语句中替换model的值?
答案 0 :(得分:1)
尝试:
model_ids = model.constantize.where("opportunity_id = ? ", $current_opportunity)
constantize也适用于符号