1

I have two resources: FaxRequest and InternetRequest that both inherit from Request. I generated each of the three resources using the rails scaffold resource command and then modified the models to inherit from Request like this:

#request.rb
class Request < ActiveRecord::Base
end

#fax_request.rb
class FaxRequest < Request
end

#internet_request.rb
class InternetRequest < Request
end

I would like to have a view that has a table showing all Requests (both FaxRequests and InternetRequests) together. I have this implemented as the index view of the Request controller.

#request_controller.rb
def index
  @requests = Request.all
end


#views/requests/index.html.haml
=@requests.each do |request|
  = request.date
  = link_to('show', request)
  = link_to('edit', ?)
  = link_to('delete' ?)

I see that link_to('view', request) is smart enough to generate a link to the appropriate resource, but how does Rails know whether to generate an edit_fax_request_path(request) or edit_internet_request_path(request) based on the subclass of the request? Same goes for new and delete?

Secondarily, I'm curious to know what the idomatic approach to STI is. One controller or three in this case? Am I going about the problem all wrong. It seems to me that Rails would have a tidy way of dealing with this problem, yet I've googled and can't find anything. Perhaps I'm not asking the right question?

rswolff
  • 3,258
  • 5
  • 28
  • 31

1 Answers1

4

All you need to do is to use the edit_request_path(request) helper method for the edit link. As for the delete link, here is the delete link code that scaffolding would of generated and will work, once you do as I outline below:

= link_to( 'Destroy', request, :confirm => 'Are you sure?', :method => :delete )

Then edit your routes file telling rails to generate the appropriate routes to go to the request controller like so (note, you might not need the map part):

map.resources :requests
map.resources :fax_requests, :controller => :requests
map.resources :internet_requests, :controller => :requests

This way all the routes are generated as you would expect and they all go to the main controller that they inherited from.

Update: Found a great article talking about this (and warns about some of what I say)

http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html http://stackoverflow.com/questions/4507149/best-practices-to-handle-routes-for-sti-subclasses-in-rails

iansheridan
  • 431
  • 3
  • 8