Is it real in RoR?


#1

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”
end

class ólassification < ActiveRecord::Base
set_table_name “dic”
end

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

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
found.

Can I add it with RoR?


#2

On Nov 18, 8:00šam, Alexey removed_email_address@domain.invalid 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 }

end

Example usage

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

Jeff

purpleworkshops.com


#3

Hello–

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
(http://wiki.rubyonrails.org/rails/pages/singletableinheritance
). 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
end

class Category < Dic
end

class Classification < Dic
end

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

cls = Classification.create(:some => ‘other_value’, :that =>
‘makes_different_sense’)

Category.find(:all)
=> [#<Category id: 1, :some: “value”, that: “makes_sense”, type:
“Category”>]

Classification.find(:all)
=> [#< Classification id: 2, :some: “other_value”, that:
“makes_different_sense”, type: Classification">]

Dic.find(:all)
=> [#<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.