Rails : Formtastic : Single Table Inheritance : Issues and solution

I have been using Formtastic from the beginning and then some feature changes came across my application. I had a model called `DrugTest` then I also needed to implement additional drugtest (hair test and alcohol test). So I thought STI would be a perfect match to my scenario.

I created two classes `AdditionalHairDrugTest` and `AdditionalAlcoholDrugTest` derived from the model `DrugTest`

# == Schema Information
#
# Table name: drug_tests
# type :string
# ...
class AdditionalAlcoholDrugTest < DrugTest
 belongs_to :pact
 belongs_to :user
 default_scope -> {where(type: :AdditionalAlcoholDrugTest)}

 def is_additional?
   true
 end
end

Now I encountered this error

Routing Error

uninitialized constant Admin::AdditionalHairDrugTestsController

Reason: In my view I had

= semantic_form_for [:admin, @drug_test] do |f|

Since the class of @drug_test object was `AdditionalHairDrugTest` so the `semantic_form_for` method expects `AdditionalHairDrugTestsController` to be present which was not there.

One solution would be creating separate AdditionalHairDrugTestsController derived from DrugTestsController. But I would need to create new controller for every drug test type I add later in my system.

best solution would be using `as` clause in  `semantic_form_for` like

= semantic_form_for [:admin, @drug_test], url: admin_drug_test_path(@drug_test), as: :drug_test do |f|

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s