开发者

Broken Rails Routes after implementing Single Table Inheritance

开发者 https://www.devze.com 2023-01-30 03:50 出处:网络
I have implemented single table inheritance for a person class class Person < ActiveRecord::Base end

I have implemented single table inheritance for a person class

class Person < ActiveRecord::Base

end


class Teacher < Person

end

class Student < Person

end

class Outsider < Person

end

And the create person seems to work creating Teacher, Student or Person according to the what is chosen in the form.select a开发者_开发知识库nd the type attribute is added.

However, I seem to have broken the routes

<%= link_to 'Edit', edit_person_path(@deal) %> | <%= link_to 'Back', persons_path %>

They seem to point to teacher_path, student_path and outsider_path instead of person_path.

What changes need to be made in the routes?


first generate controllers for your models...

rails generate controller Persons
rails generate controller Teachers
rails generate controller Students
rails generate controller Outsiders

then in routes.rb (rails 3)

resources :persons
resources :teachers
resources :students
resources :outsiders

gives you REST routes

e.g.

persons GET    /persons(.:format) {:action=>"index", :controller=>"persons"}
new_person GET    /person/new(.:format) {:action=>"new", :controller=>"persons"}
edit_person GET    /persons/:id/edit(.:format) {:action=>"edit", :controller=>"persons"}
person GET    /persons/:id(.:format) {:action=>"show", :controller=>"persons"} 
persons POST   /spersons(.:format) {:action=>"create", :controller=>"persons"}    
person PUT    /persons/:id(.:format) {:action=>"update", :controller=>"persons"}    
person DELETE /persons/:id(.:format) {:action=>"destroy", :controller=>"persons"}

the same for teacher, student and outsider

check rake routes or rake routes | grep teachers


From my experience, it's better to use a single controller for all the STI models. If you're keeping your controllers DRY, you shouldn't need to have unique controller logic for each child class. Keep all that in the models.

resources :people

Your named routes will be like:

people_path
new_person
edit_person
person
etc...

Then you can use the same controller/views to manage these models. If you decide later to add new Person STI models, you won't have to make any significant updates to your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消