4

I have legacy Sql Server database and Rails applications. Column names in database are all in PascalCase (FirstName, CustomerId...).

I'm searching for an easy way to use underscore_casing in Ruby and PascalCasing in database. I would like to write first_name in Rails for FirstName column in database.

camelize and underscore will convert a string to required casing

but I'm looking for something more general like: ActiveRecord::Base.camelize_table_column_names = true

like existing ActiveRecord::Base.pluralize_table_names

Just like translating Ruby in rjs templates to JavaScript cameCase convention.

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76

2 Answers2

3

Maybe set up aliases for all defined column names?

column_names.each do |column_name|
  alias_attribute column_name.underscore, column_name
end

You could add that to a concern and include that concern in all relevant models.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • +1, but there might be a slight issue with including the concern, this must happen after `table_name` is set if the table name does not match the class name. – Slicedpan Apr 26 '16 at 09:36
  • Good point. Though you can just add that table name bit to the concern too. – Michael Kohl Apr 26 '16 at 15:34
2

I don't think there is a single option that would switch on such behavior. Rails, after all, obeys the convention over configuration principle but not all internal conventions are configurable.

On the other hand you should be able to define column aliases for all of your columns, e.g:

class Customer < ActiveRecord::Base
   alias_attribute :first_name, :FirstName
   # etc...
end

This way Rails should transparently "translate" the underscore attributes to CamelCase ones:

Customer.where(first_name: "John")
# => SELECT `customers`.* FROM `customers` WHERE `customers`.`FirstName` = 'John'
Matouš Borák
  • 15,606
  • 1
  • 42
  • 53