I would like to dynamically add attributes to a Ruby on Rails object so I can access them with an Ajax call. I understand that I can send the info with another Ajax call, but I would much prefer to add the :first_name
and :avatar_url
attributes dynamically. Here is my code...
def get_info
comments = []
allTranslations.each do |trans|
if trans.comments.exists?
trans.comments.each do |transComment|
user = ...
class << transComment
attr_accessor :first_name
attr_accessor :avatar_url
end
transComment.first_name = user.first_name
transComment.avatar_url = user.avatar.url
comments.push(transComment)
puts("trans user comments info")
transComments.each do |x|
puts x['comment']
puts x['first_name']
puts x.first_name
puts x['avatar_url']
end
end
end
end
@ajaxInfo = {
translationUsers: allTranslations,
currentUserId: @current_user.id,
transComments: transComments
}
render json: @ajaxInfo
end
Out of the 4 print statements, only puts x.first_name
prints, and none of the attributes are added to the objects when I log the results on my console.
Here is the corresponding Javascript and Ajax:
$('.my-translations').click(function(){
$('#translation').empty();
getTranslations(id).done(function(data){
console.log(data)
var transUsers = []
...
});
});
function getTranslations(translationId) {
return $.ajax({
type: "GET",
url: '/get_translations_users',
data: {
translationId: translationId
},
success: function(result) {
return result;
},
error: function(err) {
console.log(err);
}
});
};
Any tips or advice is appreciated! Thanks :)