Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I rename a field on a model without running migrations or altering the database?

Jay Killeen asked in Rails

Hi

I have a rails app that sits over an existing SQL Server database that I have no control over. Purely read only access to.

I have a model like Customer with fields like CustomerCode, CustomerName etc. Which means ugly unconventional Customer.first.CustomerCode and Customer.first.CustomerName.

Is there a way in the app/models/customer.rb to rename these columns so I can instead call Customer.first.id and Customer.first.name

Hopefully this is very straightforward.

Thanks

Reply

I am thinking it will be some kid of alias method on the model that emulates SQL AS

Essentially I am hoping to be able to use customer.id and rails knows I am meaning customer.CustomerCode or when ActiveRecord runs the SQL it passes something like

SELECT [dbo].[dimCustomer].[CustomerCode] AS [id] FROM [dbo].[dimCustomer];
Reply

Hey Jay,

You should be able to use alias_method

alias_method 'CustomerName', 'name'

Check out: https://blog.bigbinary.com/2012/01/08/alias-vs-alias-method.html

Reply

Thanks Jacob,

I did have a read of this and have implemented it in my app for now. Would be nice to be able to get the ActiveRecord query builder to also use the SQL 'AS' alias method too so that it asks for:

SELECT [dbo].[dimCustomer].[CustomerCode] AS [id] FROM [dbo].[dimCustomer];

At the moment it will still send

SELECT [dbo].[dimCustomer].[CustomerCode] FROM [dbo].[dimCustomer];

And in BetterErrors if I inspect the Customer object it still refers to methods as the unaliased name.

But works for now so Thank You.

Reply

Ahh, that's an interesting distinction there.

After some Googling, I came across alias_attribute I haven't tried it, but from what I'm gathering it looks like it may solve your issue.

Check out: http://www.chrisrolle.com/en/blog/aliasing-the-rails-way

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 82,464+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.