Broken Rails Routes after implementing Single Table Inheritance

☆樱花仙子☆ 提交于 2019-12-12 08:15:02

问题


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 and 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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/4432858/broken-rails-routes-after-implementing-single-table-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!