Search code examples
ruby-on-railsjsonattr-accessor

Adding additional data to an ActiveRecord object


I'm retrieving a "Widget" ActiveRecord object:

@widget = Widget.find(params[:id])

I want to add some extra data to it before I return it, so I'm adding it using:

@widget.display_name = "test display name"

I can then do puts @widget.display_name and this indeed does display "test display name", but when I call puts @widget.inspect it does not include the extra data.

I was originally getting:

NoMethodError (undefined method `display_name=' for # <Widget:0x007fe6147e8e00>):

but I included attr_accessor :display_name on the Widget model and that stopped that particular message.

Just to be clear, I don't actually want to store this extra data in the database, but rather just return it as a JSON object. I'm rendering the JSON using render json: @widget, status: :ok and this is also not including the extra data.

For clarity, here is my code:

def show
    @widget = Widget.find(params[:id])
    @widget.display_name = "test display name"
    puts @widget.display_name # displays "test display name"
    puts @widget.inspect
    if @widget
      render json: @widget, status: :ok
    else
      head :not_found
    end
  end

Solution

  • You can try merging the display_name into @widget's attributes:

    @widget = @widget.attributes.merge(display_name: "test display name")
    render json @widget
    

    The above should return a JSON object of @widget's attributes, including the specified display_name.

    Hope it helps!