开发者

Class Inheritance or Single Table Inheritance in Rails 2.3

I have the following scenario and I'm not sure if I should use Class Inheritance or Single Table Inheritance:

Class User
  has_one :main_list
  has_one :known_list
  has_many :regular_lists
end

Class List
  has_many :words
end

Class Wo开发者_开发知识库rd
  belongs_to :list
end

What I would like to do is have each different list type be a different class, the problem is that if I do that, I would need to add main_list_id, known_list_id, and regular_list_id to the Word object/class. This seems cumbersome. Can I do something like:

Class MainList
  has_many :words, :foreign_key => list_id
end

and then something like:

@user.main_list.find_by_name("MainList") ?

The only problem with this is that someone could name a RegularList "MainList".


You could do something like this:

Class User < ActiveRecord::Base
   has_many :lists
end

Class List < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :words
end

Class Word < ActiveRecord::Base
  has_and_belongs_to_many :lists
end

On the list class you could add two boolean fields to list; one for main_list and the other for known_list. On that class you could also add validations to make sure that each user only has one main list and one known list. To select the main list for a user you could do:

@user.lists.find(:first, :conditions => {:main_list => true})
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜