2017-08-01 109 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

由於以下解決了這個問題!