我正在尝试使用rails中的private-pub gem创建一个基本的聊天客户端。我尝试实现的功能如下所示。这里有一个在线用户列表,如代码below.Every user is subscribed to own private channel所示。为了让用户向另一个用户发送消息,他必须从在线用户列表中选择一个用户,然后发送message.When。然后,获取作为在线用户的类名的userid,并尝试发布消息。要发布此消息,我需要将其发送到他订阅的频道,我需要将从javascript变量获取的用户id变量转换为ruby变量。
<%= subscribe_to "/messages/#{current_user.id}" %>
<h1>Messages</h1>
<% if user_signed_in? -%>
<div class="row">
<div class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list userlist">
<% for user in User.all -%>
<% if user.online? and user.id!=current_user.id -%>
<li><%= link_to '#',:class => user.id ,:remote=>true do %>
<%= image_tag user.profile.picture(:thumbnail_medium) %>
<%= user.profile.name %>
<% receiver = user.id -%>
<% end %>
</li>
<% end -%>
<% end -%>
</ul>
</div>
</div>
<div class="span8 well well-small">
<div id="chatwindow">
<div id="messagewindow">
<ul id="chat">
<%= render @messages %>
</ul>
</div><br>
<div id="inputcontainer"><%= form_for Message.new, :remote=>true, :url => {:controller=>:messages,:action =>:create } do |f| -%>
<%= f.label :Message %>
<%= f.text_field :content %>
<%= f.submit "Submit" %>
<% end -%> </div>
</div>
</div>
</div>
<% else -%>
<% end -%>Java脚本如下所示:
$(function(){
$('.userlist li').click(function() {
$(this).siblings('li').removeClass('active');
$(this).addClass('active');
});
});这是用于发布消息的嵌入式js。
receiver = $('.active a').attr('class').
<% publish_to "/messages/"+receiver do -%>
$('#chat').append('<div class="well well-small"><%= j link_to (image_tag(current_user.profile.picture(:thumbnail))),username_path(current_user.username) %><%= j link_to current_user.profile.name, username_path(current_user.username) %> <%= " #{@message.content}" %></div>')
<% end -%>
$('#new_message)[0].reset();为了创建通道,我使用jquery获取receiver,我需要将其转换为ruby,然后传递给publish函数,即problem.Is。有什么方法可以将这个javascript变量转换为ruby变量吗?实现该功能的任何其他想法将不胜感激:)
发布于 2013-03-02 16:48:49
我是通过向控制器发送一个ajax请求来实现的。无论何时在聊天窗口中选择一个用户(从在线用户列表中),我都会将这些参数发送到控制器,并通过一个隐藏字段将其保存在我的模型中,方法是使用jquery.Now的值,上面提到的javascript变量可以通过ruby访问。
谢谢:)
发布于 2013-03-01 01:06:15
Opal是目前市面上最好的Ruby到JavaScript的转换器/编译器。你可以在这里看到它的实际效果:http://goo.gl/f6f1D
https://stackoverflow.com/questions/15140675
复制相似问题