2017-08-01 113 views
0

我想动态地将属性添加到R​​uby 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); 
     } 
    }); 
}; 

任何提示或建议表示赞赏!谢谢:)

回答

0

出了4条print语句,只有把x.first_name打印

这是因为,当你调用X [ '注释']等你调用x对象上的[]方法我不认为这个对象是一个散列。当你调用.first_name时,你使用动态创建的新的attr_accessor;我想也是。 avatar_url应该可以工作。

请问如果你这样做,而不是它的工作:

@ajaxInfo = { 
    translationUsers: allTranslations, 
    currentUserId: @current_user.id, 
    transComments: comments 

} 
+0

谢谢你的帮助!我发现了一个很好的解释和修复在这里:https://stackoverflow.com/questions/18429274/how-to-add-new-attribute-to-activerecord ...事实证明,'attr_accessor'创建属性,而不是哈希因此它使用'.'语法。我最终使用了Chris Kerlin的解决方案。 –

0

我发现这个真棒主题,回答我的问题:How to add new attribute to ActiveRecord

正如@CuriousMind attr_accessor表示创建属性,而不是哈希。

我通过该解决方案通过@克里斯Kerlin

由于以下解决了这个问题!