Search code examples
mysqlruby-on-railsrubyruby-on-rails-5postman

Rails 5 Column Named Root Misbehaving


I am attempting to create a restful API in Rails 5, one of my classes has an attribute named root. This root attribute has caused a few errors, I will provide one example. Is root a protected attribute name in rails or ruby?

class ObjectsController < ApplicationController
  before_action only: %i[create]

  def create
    @object = Object.create(object_params)
    render json: @object
  end

  private


  def object_params
    params.require(:object).permit(:id, :root)
  end

When I post to /objects/ with something like the following:

{"object": {"id": "manual_id" , "root": "manual_root"}}

I am returned with the following in Postman:

{
    "id": "manual_id",
    "root": null,
    "extension": "manual_extension"
}

But in the MySQL database the value for root is manual_root. Has anyone any ideas of what the issue may be.


Solution

  • The solution was to add an attribute alias to the model like so:

    class Object < ApplicationRecord
      alias_attribute :object_root, :root
    end
    

    and use this attribute in the object serializer class:

    class ObjectSerializer < ActiveModel::Serializer
      attributes :id, :object_root
    end
    

    So my problem was with the active model serializer, I believe that root is a reserved keyword. Here is a similar issue: https://github.com/rails-api/active_model_serializers/issues/1135