0

I need a def in my application_helper.rb that will accept the model name passed as a variable.

I have a nav view where i am trying to access a particular record based on the content of $current_opportunity

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

What I was trying to do was call get_id and pass 'Lab' to it.

My application_helper.rb has

 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

If I try to run like that, I get

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'

However, if I change the def to

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

i.e hard wiring Lab, everything works.

Is there any way to substitute the value of model in the where statement?

1 Answer 1

1

Try:

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

constantize also works with symbols

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.