我想动态地将属性添加到Ruby on Rails对象,以便我可以通过Ajax调用访问它们。我知道我可以用另一个Ajax调用发送信息,但我更愿意动态添加:first_name
和:avatar_url
属性。这里是我的代码...使用Ajax动态添加属性到RoR对象
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
出了4 print语句,只有puts x.first_name
打印,并且没有任何属性都加入到对象时,我登录我的控制台上的结果。
下面是相应的JavaScript和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);
}
});
};
任何提示或建议表示赞赏!谢谢:)
谢谢你的帮助!我发现了一个很好的解释和修复在这里:https://stackoverflow.com/questions/18429274/how-to-add-new-attribute-to-activerecord ...事实证明,'attr_accessor'创建属性,而不是哈希因此它使用'.'语法。我最终使用了Chris Kerlin的解决方案。 –