Yoann Picquenot Yoann Picquenot - 1 year ago 81
Ruby Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download