Ruby on Rails "render json:" ignoring alias_attribute Ruby on Rails "render json:" ignoring alias_attribute json json

Ruby on Rails "render json:" ignoring alias_attribute


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)


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