0

I'm building this little app with ruby on rails. In the app, I'm having the following models strutter which I'm not sure whether it's the best ror practice. (I'm actually a Java developer)

There is a person class which I use it as a super class, and there are staff class and customer classes inherits from the person class. To achieve this, I have:

class Person < ActiveRecord::Base
end

class Staff < ActiveRecord::Base
    belongs_to :person, :polymorphic => true, :dependent => :destroy 
end

class CreateStaffs < ActiveRecord::Migration
  def self.up
    create_table :staffs do |t|
      t.references :person, :polymorphic => true, :null => false 
      ....

Firstly, what I did works fine, but am i doing the best thing?

The next thing I'm trying to do is to create a form which creates person, staff objects and link them. And I'm stuck on having two models on a single form. Does anyone have suggestions?

Thanks, Kevin Ren

1 Answer 1

1

What you're doing here is not to use Person as a superclass of Staff, but you create a relation between them. You want to look at single-table inheritance instead. You essentially want this:

class Person < ActiveRecord::Base
end

Class Staff < Person
end

In addition you need to have a "type" field in your Person table that Rails uses to figure out which model a given record belongs to. See the docs for ActiveRecord for more info.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks harald, I have one question based on the model you suggested. Say i have the username field for Staff. Since Staff is actually in the Person table, how can i prevent Person from accessing the username field?
@Kevin, you may want to ask this as a separate question so perhaps more people will see it and answer. I think your only option is to use validations, or to override the access methods (Person.username and Person.username=. Here's a good article about STI: code.alexreisner.com/articles/…
thanks @harald, i'll remember to ask separate question next time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.