Satchel
Satchel

Reputation: 16724

How do I create the Controller for a Single Table Inheritance in Rails?

I am setting up the Single Table Inheritance, using ContactEvent as the Model that ContactEmail, ContactLetter, and ContactCall will all inherit.

But I'm stumped on how to create the routing and the controller.

For example, let's say I want to create a new ContactEvent with type Email.

I would like a way to do the following:

new_contact_event_path(contact, email)

This would take the instance from Contact model and from Email model.

Inside, I would imagine the contact_event_controller would need to know...

   @contact_event.type = (params[:email]) # get the type based on what was passed in?
   @contact_event.event_id = (params[:email]) #get the id for the correct class, in this case Email.id

Just not sure how this works....

Upvotes: 1

Views: 2668

Answers (2)

Joao Pereira
Joao Pereira

Reputation: 2534

I had similar problem.

See here how I solved it.

Upvotes: 3

tsdbrown
tsdbrown

Reputation: 5058

I would have a controller (and maybe views) for each of your resource types. So add a controller for ContactEmail one for ContactLetter etc. Don't bother with one for the base class ContactEvent. Then your paths would read something like:

new_contact_email_path(@contact) or new_contact_letter_path(@contact)

The controller actions would then use the right model for that they represent, ie:

@contact_email = ContactEmail.new(params[...])

If you can keep your three types of resources separate rather than trying to pass the type in and building the right object in one controller you should find life much easier. The downside is you may need more links/forms/views in the front end, however depending on your application that may not be a bad thing from the user's perspective.

Upvotes: 0

Related Questions