Carlos Agudelo
Carlos Agudelo

Reputation: 13

How to create an attribute which will be persisted in all ActiveRecords (Rails)?

I want to add an attribute, which will be persisted in my database, to all my models classes in a Ruby on Rails project. I want something just like the created_ad and updated_at attributes, but I don't know how this is possible, or even if it is.

Do I have to add the attribute and column manually to all my models, or is there a better way to do this?

Upvotes: 1

Views: 103

Answers (2)

max
max

Reputation: 102001

For an existing project there is no way around generating the migrations for each model. You could possibly write a rake task to automate this by looping through the files in app/models and using a heuristic based on the rails naming conventions to generate migrations.

names = Dir.glob(Rails.root.join('app', 'models', '*.rb')).map do |p|
  Pathname.new(p).basename.to_s.chomp('.rb')
end.reject {|p| p == "application_record"}
models = names.map { |n| n.classify.constantize }
models.each do |m|
  next unless m.ancestors.include?(ActiveRecord::Base)
  puts %x{ rails g migration add_foo_to_#{m.table_name} foo:string }
end

This is a (very) simplified example that does not take "namespaced" models into account or handle errors.

For a greenfield project or new models you can create your own generators which would add the additional column when you run the standard rails generator commands such as rails g model.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

You'll have to run a migration (or several) that will add the column to all needed models. No way around this.

As for how to go about the migrations: you are limited only by your imagination. The simplest way is to simply write out all migrations manually, a migration per table.

You also could write a script that will generate the migration files for you. Or do it all in the same migration: just call add_column in a loop.

Upvotes: 2

Related Questions