简体   繁体   English

在javascript中追加ruby partial,并传递一个rails变量

[英]Append ruby partial in javascript, and pass a rails variable

Creating a chat component with ActionCable in Rails5. 在Rails5中使用ActionCable创建聊天组件。 I learned today that render partial, even in .js.erb does supposedly doesn't work. 我今天学到了渲染部分,即使在.js.erb中也应该不起作用。 render specifically is the issue. 具体render是问题。 So now I'm trying to call a partial, and pass a ruby variable to it. 所以现在我试图调用一个部分,并将一个ruby变量传递给它。

I have tried many things, currently this is how I'm trying to accomplish it: 我尝试了很多东西,目前我正在努力实现它:

chatbox.append(<%= j (Erubis::Eruby.new(File.read(File.join(Rails.root, 'app/views/msgs',
        '_msg.html.erb'))).result(msg: @msg)) %>);

and the error is 而错误是

 undefined method `self_or_other' for #<Erubis::Eruby:0x007f832bbb8590>

So the partial is there, but the variable is not correct. 所以部分存在,但变量不正确。


views/msgs/_msg.html.erb 视图/封邮件/ _msg.html.erb

<li class="<%=  self_or_other(msg) %>">
  <div class="avatar">
    <%# if msg_interlocutor(msg).avatar.url(:thumb) == "thumb/missing.png" %>
    <%= image_tag(msg_interlocutor(msg).avatar.url(:thumb), class: "convoPic")%>
</div>
</li>

I also tried: 我也尝试过:

chatbox.append(<%= j (Msg.new(File.read(File.join(Rails.root, 'app/views/msgs',
        '_msg.html.erb'))).result(msg: @msg)) %>);

And get this error: When assigning attributes, you must pass a hash as an argument. 并得到此错误: When assigning attributes, you must pass a hash as an argument.

Trying with render: 尝试使用渲染:

App.msgs = App.cable.subscriptions.create('MsgsChannel', {  
  received: function(data) {
    var chatbox = "#chatbox_" + data.convo + " .chatboxcontent"
    var id = data.convo;
    var sender_id = data.user.id;
    var reciever_id = data.receiver;
    <%= @msg %> = data.msg
    $(chatbox).append("<%= escape_javascript render(:partial => 'msgs/msg', :locals => { :msg => @msg }) %>");

    chatbox.scrollTop(chatbox[0].scrollHeight);
  },
  renderMsg: function(data) {
    console.log(data)
  }
});

And error I receive: 我收到的错误:

undefined method `render' for #<#<Class:0x007fe976b5c180>:0x007fe9773ed470>

How do I properly call in a partial, pass it a ruby variable (with the msg record). 如何正确调用partial,将其传递给ruby变量(使用msg记录)。 Thank you!! 谢谢!!

do you have a "messages_helper.rb" file with the following 你有一个“messages_helper.rb”文件与以下内容

module MessagesHelper
  def self_or_other(message)
    message.user == current_user ? "self" : "other"
  end

  def message_interlocutor(message)
    message.user == message.conversation.sender ? message.conversation.sender : message.conversation.recipient
  end
end

This is where it's defined. 这是它定义的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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