14

I am using Single Table Inheritance and have comments on all the subclasses. I am only using 1 controller for all the different STI types. When the form_for helper generates a URL for a subtype it tries to use a helper for the subtype, but I want it to use the helper for the parent.

This is the error I get:

undefined method `subclasstypename_comments_path' for #<ActionView::Base:0x41ef27c>

The path helper it 'should' use is

parentclasstypename_comments_path
Kyle Boon
  • 5,213
  • 6
  • 39
  • 50

1 Answers1

61

Yep, just use AR::Base#becomes.

Say your base class is Account, which is subclassed to GuestAccount and LoginAccount.

@account.is_a? LoginAccount? #=> true

Then you can just do a

form_for [@account.becomes(Account), @comment] do |f|
  ...
ben_h
  • 4,424
  • 1
  • 20
  • 11
  • the form renders correctly with correct path but nothing gets saved when I submit the form – lulalala May 28 '12 at 06:47
  • this is utterly awesome. – m_x Sep 20 '13 at 12:20
  • Link to documentation -> [ActiveRecord::Base.becomes](http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-becomes) – Nate Oct 06 '14 at 14:22
  • Since the link to Henrik's blog post isn't working anymore, I just want to reiterate that this has some issues. If you have an object with associated has_many children, the validations and error messages are lost when you call the new object in the form. – Serena Nov 03 '14 at 21:58
  • Working link to Henrik's post: http://thepugautomatic.com/2012/08/rails-sti-and-form-for/ – bfcapell May 13 '16 at 20:27