Ruby on Rails Wednesday, April 4, 2012

On 3 April 2012 18:32, Fearless Fool <lists@ruby-forum.com> wrote:
> (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?
>
> 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?

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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment