Forum: Ruby on Rails Is it real in RoR?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
295f1be093bf8042dd523d65f9306355?d=identicon&s=25 Alexey (Guest)
on 2008-11-18 17:05
(Received via mailing list)
I've a table dic: id, type_id, info

I'd like to store any information inside, it can be, for instance,
categories with type_id = 1 and classifications with type_id = 2

I'd like to make 2 different models such as

class Category < ActiveRecord::Base
  set_table_name "dic"

class ólassification < ActiveRecord::Base
  set_table_name "dic"

and add conditions to it: type_id = 1 to first, type_id  = 2 to

In this way i can use Category.find(:all) and don't care about
classification - they won't be found.
On the other hand, in ólassification.find(:all) categories won't be

Can I add it with RoR?
8217faf2bfdfa7daf10135d41ddd421e?d=identicon&s=25 Jeff Cohen (jeff)
on 2008-11-18 18:01
(Received via mailing list)
On Nov 18, 8:00šam, Alexey <> wrote:
> found.
> Can I add it with RoR?

I'd suggest you use named scopes instead, allowing you to stick with
Rails conventions and benefits.

class Dic < ActiceRecord::Base
 set_table_name 'dic'

 named_scope :categories, :conditions => { :type_id => 1 }
 named_scope :classifications, :conditions => { :type_id => 2 }


# Example usage

Dic.categories.all # => returns all categories
Dic.classifications.all # => returns all classifications

Ef0db53920b243d6758c2f6b1306df0d?d=identicon&s=25 Steve Ross (cwd)
on 2008-11-20 08:59
(Received via mailing list)

On Nov 18, 2008, at 6:00 AM, Alexey wrote:

> end
> On the other hand, in Сlassification.find(:all) categories won't be
> found.
> Can I add it with RoR?

Apologies if this has already been answered.

It looks like you want single table inheritance
). So, if I understand your question correctly, you would have a
column "type" (not "type_id") in your table and write this code:

class Dic < ActiveRecord::Base

class Category < Dic

class Classification < Dic

# ...

cat = Category.create(:some => 'value', :that => 'makes_sense')

cls = Classification.create(:some => 'other_value', :that =>

=> [#<Category id: 1, :some: "value", that: "makes_sense", type:

=> [#< Classification id: 2, :some: "other_value", that:
"makes_different_sense", type: Classification">]

=> [#<Category id: 1, :some: "value", that: "makes_sense", type:
"Category">, #< Classification id: 2, :some: "other_value", that:
"makes_different_sense", type: Classification">]

Because these are different classes they can have different behaviors
over and above what is provided in the base class. So, not only does
this select rows cleanly, it also allows you to model the behavior
according to the type of the data.
This topic is locked and can not be replied to.