开发者

Form helpers in case of Single Table Inheritance

I have to implemene Single Table Inheritance for a class Person who can be of type Teacher, Student,Outsider.

class Person < ActiveRecord::Base

end


class Teacher < Person

end

class Student < Person

end

class Outsider < Person

end

What changes do I need to make in the routes and the forms while register a new user. I have a column(string) "type" in the people table which can be implemented as a dropdown in the form to register a 开发者_运维百科new user. Is there anything else that I need to do in the form so the user is registered as a particular type of Person? Do I need to make any changes in the routes too?


Since you use one form to create all types of Persons, then you should stick with one Controller as well so you don't need to add any additional routes.

The type attribute is not really something you should assign manually to an instance, it should be set automatically by choosing which type of model to create.

I don't know how it looks in your controller and views, but you can extract the type of model to create like this:

class_type = params[:type].constantize
@person = class_type.new

On the other hand, if the type attribute is nested in a form_for in your view, then the type attribute is probably send to the controller like params[:person][:type] in which case it should be removed from the :person hash before it is used to create the new instance. Perhaps something like this:

class_type = params[:person].delete(:type).constantize
@person = class_type.new(params[:person])


Except adding a dropdown list of type selection in the form, there's nothing more to do. You can create a user in the normal way, like:

@user = Person.new params[:user]

But the type attribute could not be mass assigned, so you have to assign it separately.

@user.type = sanitize_user_type params[:user][:type]

The method sanitize_user_type is used to validate user input value.

The route for creating new user doesn't need to change. Whether other routes need to change or not depend on your requirement. Actually you can add the routes for Teacher, Student, Outsider and relative controllers, so that you can build restful urls.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜