Ruby on Rails "render json:" ignoring alias_attribute

Viewed 1573

I have the following code in my account.rb model file:

class Account < ActiveRecord::Base
  alias_attribute :id, :accountID
  alias_attribute :name, :awzAccountName
  alias_attribute :description, :awzAccountDescription
end

And the following code in the index method from my accounts_controller.rb file:

def index
    @accounts = Account.all

    if params["page"]
      page = params["page"]
      items_per_page = params["per_page"]

      render :json => {:total => @accounts.count,:accounts => @accounts.page(page).per(items_per_page) }
    else
      render json: @accounts
    end
end

As expected, render json: @accounts returns a result set that contains the alias_attribute column names defined in the model file. However, the render :json => {:total => @accounts.count,:accounts => @accounts.page(page).per(items_per_page) } code returns a result set that contains the original column names. Is there any way to change this so that the alias_attribute column names are used?

2 Answers

I was able to solve this by overwriting serializable_hash method.

def serializable_hash(options = {})
  options[:methods] ||= []
  options[:methods] += [:name, :description]
  super(options)
end

You can achieve the same result by passing methods argument to as_json without changing your default serialization of your models. like this:

render json: @accounts.as_json(methods: [:name, :description])
Related