Giant Japanese Robot

Better living through pop culture.
Sep 01
Permalink

Ruby on Rails: Single Table Inheritance and Restful Routes

I am writing this out of a bit of frustration. I have a solution here, but it took too long and it can not be correct. I am hoping some smarter folks will chime in with some thoughts.

I have a model called Questions which has many subtypes using single table inheritance. Basically types of questions dropdown, checkbox, radio, etc etc.

These are set up as resources so I can use restful routing. I also want to use all of the rails form magic so I set up resources like this…

 map.resources :question_checkboxes, :as => :questions, :controller => :questions

This allowed the form_for method to render the form correctly and point to the “question” url instead of the url of one of the subtypes.

The next problem was that the “update” controller method was looking for very specific params “params[:question]”, but the rendered form was passing params like “params[:question_checkbox]”. The way I eventually solved this was set up a before filter and method in the controller like this…

 before_filter :form_symbol

   def form_symbol
      if params[:question] then @form_symbol = :question end
      if params[:question_checkbox] then @form_symbol = :question_checkbox end
   end

and then in the update method of the questions_controller

 @question.update_attributes(params[@form_symbol])

It does the trick, but feels very uncomfortable. Suggestions and comments are welcome.

Comments (View)

blog comments powered by Disqus