开发者

Association models managing classes in a "uncommon way"

开发者 https://www.devze.com 2023-03-03 01:32 出处:网络
I am using Ruby on Rails 3 and I have a class List and some other child classes that \"compose\" that List in a \"uncommon way\". That is, I have a List model with the following attributes:

I am using Ruby on Rails 3 and I have a class List and some other child classes that "compose" that List in a "uncommon way". That is, I have a List model with the following attributes:

# LIST ATTRIBUTES
id       : integer
kind_of  : string
class_id : integer

kind_of values can be "school", "house", ... and for each kind_of I have a class ListSchool, ListHouse, ... The class_id refers to the primary key of the child class of kind_of "school", "house", ... (so I can have multiple equal values for class_id but开发者_如何学Python each of those referring to a particular class ListSchool, ListHouse, ... depending on the kind_of value).

In few words, I would like to refer to a unique class (the class List) in order to reach all kind of child classes (ListSchool, ListHouse, ...) basing on an attribute value of the parent class (the kind_of of the class List).

How can I write the association code in order to associate those models (maybe using :conditions => "kind_of = 'school'", :conditions => "kind_of = 'house'", ... in the association statement has_one)? What do you advice about this approach of "dividing classes"?


It sounds very much like you are looking for Single Table Inheritance (STI). Rails supports this out of the box; all you need to do is define a type column on the List class, then inherit ListSchool and ListHouse from List. There is no need for the kind_of or class_id columns with STI.

A web search for 'rails sti' turns up some good resources, including this StackOverflow question.

0

精彩评论

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