简体   繁体   中英

How to replace object with coffee script?

I create users notification system and have one problem i dont know how to refresh my @activities on my header layout) I have this:

application_controller.rb

before_filter :activity

def track_activity(user, trackable, action = params[:action], author = current_user)
  Activity.create! user: user, trackable: trackable, action: action, author: author
  PrivatePub.publish_to("/messages/new", cool: activity)
end

def activity
  if signed_in?
    @activities = current_user.activities.includes(:author, :trackable).order(created_at: :desc)
  end
end

layout/_header.html.erb

<div class="user-notification">
  <a class="fa fa-life-ring fa-lg" href="javascript:void(0);" tabindex="1"></a>
  <div class="activity activity_open" id="activity">
    <% @activities.each do |activity| %>
      <%= link_to activity.user.name, activity.user %>
      <%= render "activities/#{activity.trackable_type.underscore}/#{activity.action}", activity: activity %>
    <% end %>
    <%= subscribe_to "/messages/new" %>
  </div>
</div>

javascripts/messages.js.coffee

PrivatePub.subscribe "/messages/new", (data, channel) ->
  alert $("#activity").append("<%= data.cool = @activities %>");

But alert shows [object Object]

How i can update @activities ? Please help!

You can't access instance variables in Coffeescript. If all you have to do is update a partial you could just put the append code in a file within the view directory corresponding to the action and name it the same as the action.

So if the controller is named foo and the action is named bar, you need a file called 'bar.js ' within 'controllers/foo/' that has the append code in it. That file will have access to the instance variable from the controller. You can also call Coffeescript functions from that file if you need to, but you can't access the instance variable directly from the Coffeescript file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM