Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore columns in ActiveRecord

I am trying to merge an old, legacy Rails 3 app into a more recent Django app.

Both apps used to use different databases, which are being merged into one unique database usable by both apps. The Django app will slowly take over the functionality of the old Rails app, starting with the migrations.

Django enforces strict database constraints in its migrations (e.g. NOT NULL fields with defaults). Any new fields on a table that is used by both apps will prevent Rails from updating records on that table, because ActiveRecord forcefully inserts NULL values instead of defaults.

Since we won't be adding new features to the Rails app, I'd like it to stick to a list of fields and ignore any newly-added fields.

The following answer using default_scope breaks other scopes, so I'd like to avoid it.

Triggers are an option, but I'm not keen on adding cruft to the Django app, just to deal with legacy code in the Rails app.

Hence : Can I manually define columns in my models instead of letting ActiveRecord inspect the database automatically?

like image 884
F.X. Avatar asked Jun 12 '15 08:06

F.X.


Video Answer


2 Answers

Rails 5 solves your problem by providing ignore_columns option.

class User < ActiveRecord::Base
  self.ignored_columns = %w(employee_email)
end

User.columns will not give employee_email in the output.

like image 121
Mohit Natoo Avatar answered Nov 16 '22 08:11

Mohit Natoo


You can accomplish what you want even in ancient versions of Rails (e.g. Rails 2.3) by overriding ActiveRecord::Base.columns:

class Model < ActiveRecord::Base
  def self.columns
    super.reject { |c| c.name.in?(['column1', 'column2']) }
  end
end

This is equivalent to ignore_columns in Rails 5.

like image 45
fotos Avatar answered Nov 16 '22 06:11

fotos