I am using Ruby on Rails 3.2.2 and I would like to check the presence of a database table column and the datatype (eg: String, Integer, …) of that column for a given model class. That is, I am implementing a Ruby module inside the lib directory with a method to which it is passed a model class (eg: Article) and I would like to verify just some conditions on certain related database table columns, nothing more.
In my module method I tried to use the column_exists? method as the following
module MyModule
def check_column(model_class)
table = model_class.to_s.tableize
unless ActiveRecord::Base.connection.column_exists?(table.to_sym, :title)
raise ...
end
end
end
but without success: the (strange) outputted error related to the column_exists? method is something like this
Mysql2::Error: Table '<MY_APP_NAME>_development.<A_TABLE_NAME>/<ANOTHER_TABLE_NAME>/<ANOTHER_TABLE_NAME>' doesn't exist: SHOW FULL FIELDS FROM `<A_TABLE_NAME>/<ANOTHER_TABLE_NAME>/<ANOTHER_TABLE_NAME>`
What I should make to properly check presence and datatype of database table columns at run time?
You can use
ActiveRecord::Base.connectionto send queries directly to the DBM.From that you could ask the DBM to describe a particular table, then parse the fields to find out anything about the datatypes.