Using Rails Associations in Javascript -


im trying create feed using ajax , rails gets activities of admins , alerts. when first created view used rails only, decided wanted have feed updates every time there new activity in database using ajax. ajax function works , everything, realized had alot of associations couldnt call because javascript not rails. wondering how use join replace id of query username of person created alert activity.alert.username

action: "has created alert" admin_id: null alert_id: 17 category: "alert" created_at: "2015-05-13t04:12:47.862z" id: 6 school_id: 1 updated_at: "2015-05-13t04:12:47.862z"

class activitiescontroller < applicationcontroller     before_filter :authenticate_admin!     def index         @activities = activity.where(:school_id => current_admin.school.id).order("created_at desc").limit(20)         respond_to |format|             format.json { render json: @activities}             format.html          end     end end 

old view

- @activities.each |activity|     %div.panel.panel-default         %div.panel-body             - if activity.admin_id != nil                 %span.action                     = activity.admin.email                     = activity.action             - else                 %span.action                     = activity.alert.user.username                     = activity.action              %span.timestamp                 #{activity.created_at.strftime("%b %d %y %l:%m %p")}             %span.category                 #{activity.category} 

new view

%div#activity-feed  :javascript      getactivity();      function getactivity(){          $.getjson("activity", function(data) {              for(var = 0; < data.length; i++){                 var feed = "<div class='panel panel-default'> <div class='panel-body'>" + "<span>" + data[i].action + "</span>" + "</div> </div>";             }              $("#activity-feed").html(feed);                      console.log(data);          });     }      setinterval(function() {         getactivity();     }, 5000); 

you need handle data associations in controller (i.e. rails), rails layer has access database directly. basically, want load necessary data database in controller, , send client (javascript) consume.

you can use "include" include associated objects along.

@activities = activity.include(:alert).where... 

Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -