我想動態地將屬性添加到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的解決方案。 –