views:

626

answers:

2

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
A: 

If you're always having subclass'd object, you could do this:

(Replace SuperClass with your parent class)

link_to "Comments", [@object.superclass, :comments]

If it's not always a subclass'd object you could check to see what the superclass is and go from there:

link_to "Comments", @object.superclass == SuperClass ? [@object.superclass, :comments] : [@object, :comments]

Bonus points if you put this into a helper like so:

def comments_path(object)
  object.superclass == SuperClass ? [object.superclass, :comments] : [object, :comments]
end

And then call comments_path(@object) where you need it.

Ryan Bigg
+8  A: 

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