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

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

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];

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

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.

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

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.