Summary:
I'm thinking of creating a single AR class to hold constant symbol
values and use it for :has_many_through relations whenever I need a
constant symbol. Is this a good idea or a bad idea?
Details:
I notice that I have a lot of models that contain just a name string:
create_table "natural_resources", :force => true do |t|
t.string "name"
end
create_table "roles", :force => true do |t|
t.string "name"
end
... etc ...
These moels are always joined through a has_many_through relation to
some other object (e.g. User :has_many :roles, :through => :user_roles),
and the names are treated effectively as constant symbols.
So I'm thinking of consolidating these models into a single one:
create_table :symbols, :force => true do |t|
t.string :name
end
add_index :symbols, :name, :unique=>true
class Util::Symbol < ActiveRecord::Base
validates :name, :presence => true
def self.intern(name)
(r = where(:name => name.to_s)).create!
rescue ActiveRecord::RecordNotUnique
r.first
end
end
... and using this wherever I'd previously used separate classes. This
feels DRYer.
Can anyone give a strong argument for or against this approach?
--
Posted via http://www.ruby-forum.com/.
DRYer code: this approach has fewer distinct tables, fewer distinct
classes, fewer things to test and maintain. But I may be missing
something (which is why I'm asking): what part of the code becomes more
complicated this with this approach?
Do you mean that the only thing in your roles and natural_resources
tables are the names?
If so then you could put them in one table. Consider the situation
where a role and a natural_resource happened to have the same name
however. If you decided to change the name of the role then that
would also change the name of the natural_resource.
Colin
(This is may be more of a db design question than a rails question.)Summary:
I'm thinking of creating a single AR class to hold constant symbol
values and use it for :has_many_through relations whenever I need a
constant symbol. Is this a good idea or a bad idea?