我想动态地将属性添加到Ruby on Rails对象,以便我可以通过Ajax调用访问它们。我知道我可以通过另一个Ajax调用发送信息,但我更愿意动态添加:first_name
和:avatar_url
属性。这是我的代码......
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个打印语句中,只打印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);
}
});
};
任何提示或建议表示赞赏!谢谢:))
答案 0 :(得分:0)
在4个打印语句中,只放置x.first_name打印
这是因为当你调用x ['comment']等时,你在x对象上调用[]方法,我不认为该对象是一个哈希。当你调用.first_name时,你使用动态创建的新attr_accessor;我也想。 avatar_url应该可以工作。
如果你这样做,它是否有效:
@ajaxInfo = {
translationUsers: allTranslations,
currentUserId: @current_user.id,
transComments: comments
}
答案 1 :(得分:0)
我找到了这个很棒的帖子来回答我的问题:How to add new attribute to ActiveRecord
如@CuriousMind private String keywordsList = "soup(s?)(base(s*))? hot(pot(s*))? "
+ "meat(s*) poultr((y)|(ies)){1} "
+ "beef(s?) cow(s?) ox(es)? bull(s?) "
+ "pork(s?) pig(s?) oink "
+ "mutton(s?) lamb(s?) sheep(s?) "
+ "chick(en(s)*)? hen(s)* rooster(s)* "
+ "seafood(s?) sea ocean shellfish fish((e)|(es))? "
+ "vegetable(s?) vege(s?) green plant(s?) veg(gies)? "
+ "signature(s?) recommendation(s?) recommend "
+ "h(i+) hell(o)+ y(o+) h(e)+(y) "
+ "morning afternoon evening "
+ "love(ly)? great good thank(s)? amazing excellent brilliant outstanding wonderful awesome okay "
+ "bad lousy useless stupid brainless fool(ish)? "
+ "got|get provide(s)* menu(s)* suppl(y|ies){1} offer(s*) "
+ "(good)?by(e+) leave end stop";
public String getKeywordList(){
String [] keywordsListArray = this.keywordsList.split("\\s");
String result = String.format("%-20s", keywordsListArray[0].replaceAll("[^a-z]", ""));
for (int i = 1; i < keywordsListArray.length; i++){
keywordsListArray[i] = keywordsListArray[i].replaceAll("[^a-z]", "");
if (i % 5 == 0){
result += String.format("%n%-20s", keywordsListArray[i]);
}
else
result += String.format("%-20s", keywordsListArray[i]);
}
return result;
}
所述,会创建属性,而不是哈希。
我按照@Chris Kerlin的解决方案解决了这个问题
谢谢!