开发者

Class inheritance in Ruby on Rails

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 p开发者_如何学Cerson 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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜