Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails "render json:" ignoring alias_attribute

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?

like image 622
kales33 Avatar asked Jun 03 '26 11:06

kales33


2 Answers

I wouldn't expect render json: @accounts to include the aliased attributes at all. The alias_attribute just gives you the luxury of referring to the attribute with another name - it doesn't replace the original name at all.

If you do want to include the aliases in your json output for a model you can override as_json and add those methods explicitly:

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

(I've deliberately omitted :id as that may be a special case - not entirely sure and can't test locally at the moment)

like image 105
Shadwell Avatar answered Jun 05 '26 00:06

Shadwell


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])
like image 37
vaibhavatul47 Avatar answered Jun 05 '26 00:06

vaibhavatul47



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!