Search code examples
ruby-on-railsrubyrjs

How can I use different RJS templates from the same rails controller?


I have a controller method that returns a list for a drop down that gets rendered in a partial, but depending on where the partial is being used, the RJS template needs to be different. Can I pass a parameter to the controller that will determine which RJS gets used?

Here is the controller method, it is very simple:

def services
   respond_to do |format|
     format.js {
       @type     = HospitalCriteria.find_by_id(params[:type_id])
       @services = @type.children.all
     }
   end
end

And here is the rjs template the gets rendered automatically

page.replace_html 'select_service', :partial => 'hospital/services'
page.replace_html 'select_condition', :partial => 'hospital/conditions'
page.replace_html 'select_procedure', :partial => 'hospital/procedures'

page << 'if ($("chosenType") != null) {'
  page.replace_html 'chosenType', @type.name
  page.replace_html 'chosenService', 'Selected Service'
  page.replace_html 'chosenCondition', 'Selected Condition'
  page.replace_html 'chosenProcedure', 'Selected Procedure'
page << '}'

Solution

  • What about placing the conditional logic in one rjs template?

    # services.rjs
    
    if @type == "your conditions"
      # your rjs updates
    else
      # your other rjs updates
    end
    

    This gives you a cleaner controller and saves you the headache of maintaining multiple rjs templates.