While building a JSON response with jbuilder, I want to add an attribute "image_full_url" to each of my Employee objects.
In my jbuilder file this looks like follows:
json.branch_companies @companies.select{ |branch| branch.head_company_id == head_company.id}.map{|branch| {
:branch => branch,
:employees => branch.employees.select(employee_attributes).each{ |emp| emp.image_full_url = "#{root_url[0..-2]}#{emp.photo_image.url}" },
:machine_categories => branch.machine_categories.pluck(:id, :name, :description)
}
}
In my Emplyoee Model I have a corresponding attr_accessor:
attr_accessor :image_full_url
Adding an attribute to an Employee object works perfectly on the console.
The part I having problems is here:
:employees => branch.employees.select(employee_attributes).each{ |emp| emp.image_full_url = "#{root_url[0..-2]}#{emp.photo_image.url}" }
I would expect that the "image_full_url" attribute was added to the emp object, but it isnn't. The JSON response doesn't contain the "image_full_path" field. What am I doing wrong? Can anyone help here?
Of course you will not get :image_full_url attribute in your json output, because serializer does know nothing about it. You can simply check this by doing next:
Emplyoee.limit(2).each{|e| e.image_full_url = "asdw"}.as_json
As a result, output won't contain :image_full_url attribute. If you want that attribute to be in your final result, add to that next line:
.as_json(:methods => [:image_full_url])