Yoann Picquenot
Yoann Picquenot

Reputation: 660

Rails - Convert an ActiveRecord to a simple object to add field dynamically

I am retrieving data from the database. Then I am sending it in JSON.

enter image description here

The thing is, I need to add dynamically a field "campaign_name".

def loadtimeline
    @act = Activity.order('created_at desc').paginate(:page => params[:page], :per_page => 40)

    @act.each do |item|
      item.attributes[:campaign_name] = item.campaign.name
    end

    respond_to do |format|
      format.json do
        render json: @act
      end
    end
end

Finally, the moment I check client, the new field doesn't appear.

So I told myself it could be related to this object is an ActiveRecord Model. So I am trying to convert it as an object.

Is that possible or is there a way to add the field I need?

Thank you for your help.

EDIT1. I didn't precise, but item.campaign belongs to an other model Campaign.

class Activity < ActiveRecord::Base
  belongs_to :user
  belongs_to :campaign

  attr_accessor :campaign_name

  def item
    if item_path && item_id
      case item_path
        when /todo/
          Todo.find(item_id)
        when /content/
          Content.find(item_id)
        when /netlinking/
          Netlinking.find(item_id)
        else
          nil
      end
    end
  end
end

Upvotes: 1

Views: 486

Answers (2)

Chet
Chet

Reputation: 144

a = @act.to_json
b = JSON.parse(a)
b.each do |item|
 item["campaign_name"] = item.campaign.name
end

or in a single line

JSON.parse(@act.to_json).each do |item| item["campaign_name"] = item.campaign.name end

Upvotes: 2

Anton
Anton

Reputation: 550

You could achieve this with some thing like this:

@act = Activity.includes(:campaign).order('created_at desc')  
acts = []  
@act.each do |item|  
  acts << item.attributes.merge({campaign_name: item.campaign.name})  
end  

Then render the acts array.
I think using view is clearer.

Upvotes: 3

Related Questions