2016-10-12 5 views
0

変数として渡されたモデル名を受け入れる私のapplication_helper.rbにdefが必要です。Rails - コントローラのモデル名にどのように変数を使用できますか?

私は私がやろうとした何$ current_opportunity

<%# link_to "Lab", lab_path(get_id('Lab')), class: get_labs_class() %> 

の内容に基づいて特定のレコードにアクセスしようとしていますNAVのビューを持っているが、コールGET_IDだったし、それに「ラボ」を渡します。

私application_helper.rbは、私はそのように実行しようとすると、私はつまり、ハード

model_ids = Lab.where("opportunity_id = ? ", $current_opportunity) 

にDEFを変更した場合、私は、しかし

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 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 

を持っています配線ラボ、すべてが動作します。

whereステートメントでmodelの値を代入する方法はありますか?

答えて

1

試してみてください。

model_ids = model.constantize.where("opportunity_id = ? ", $current_opportunity) 

constantizeもシンボル

で動作します
関連する問題