Column Name Alias ​​in Rails

My database has column names like "delete" or "listen-control" etc. They cannot be changed, so I would like a name alias to avoid problems in my application.

I found the following code , but it is deprecated (August 05, 2005) and does not work with Rails 3:

module Legacy def self.append_features(base) super base.extend(ClassMethods) end module ClassMethods def alias_column(options) options.each do |new_name, old_name| self.send(:define_method, new_name) { self.send(old_name) } self.send(:define_method, "#{new_name}=") { |value| self.send("#{old_name}=", value) } end end end end ActiveRecord::Base.class_eval do include Legacy end 

How can I rename column names? Is it possible?

+49
database ruby-on-rails activerecord ruby-on-rails-3
Oct 25 '10 at 13:10
source share
3 answers

Declare it in your model.

 alias_attribute :new_column_name, :column_name_in_db 
+120
Oct 25 '10 at 17:12
source share

Nicknames do not solve your problem. As I mentioned in my comment above, you cannot have a dash in the ruby ​​method or variable names, because ruby ​​will interpret them as a minus. So:

 object.listen-control 

will be interpreted by the ruby ​​as:

 object.listen - control 

and will fail. The detected code fragment may be unsuccessful due to ruby ​​1.9, and not rails 3. Ruby 1.9 does not allow you to call .send for protected or private methods anymore, for example 1.8.

At the same time, I understand that the times when the column names of the old database do not look very nice, and you want to clear them. Create a folder in the lib folder called "bellmyer". Then create a file called "create_alias.rb" and add the following:

 module Bellmyer module CreateAlias def self.included(base) base.extend CreateAliasMethods end module CreateAliasMethods def create_alias old_name, new_name define_method new_name.to_s do self.read_attribute old_name.to_s end define_method new_name.to_s + "=" do |value| self.write_attribute old_name.to_s, value end end end end end 

Now in your model that needs an alias, you can do this:

 class User < ActiveRecord::Base include Bellmyer::CreateAlias create_alias 'name-this', 'name_this' end 

And that will be right. It uses the read_attribute and write_attribute ActiveRecord methods to access these table columns without calling them like ruby ​​methods.

+6
Oct 25 '10 at 13:37
source share

As Jaime said, these names can cause problems.

In this case, use some reasonable names. Your GUI should never dictate what your columns are called.

Suggestions: is_deleted or deleted_at , listen_control

Then change your mind accordingly, this way, is easier than fighting ActiveRecord and your database.

0
Oct 25 '10 at 13:36
source share



All Articles