我有一个带有用户ID的链接。这保存在名为NameID的div中。控制器等都设置正确,但我需要做的就是能够传递NameID.innerHTML(这是一个数字)作为people.id所代表的数字。我怎么能这样做?
index.html.erb
(图未显示)
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<p><a class="btn btn-lg btn-primary" id="BtnMessageNode" href="/messages/new">Start conversation</a></p>
<h2>NameID of Node</h2>
<div id="NameID_Div"></div>
</div>
</div>
</div>
</div>
</div>
<% page_header "Users" %>
<ul>
<% @peoples.each do |people| %>
<li>
<strong><%= people.name %></strong>
<% unless current_user == people %>
<%= link_to 'Send message', new_message_path(to: people.id), class: 'btn btn-default btn-sm' %>
<% end %>
</li>
<% end %>
</ul>
messages_controller.rb
class MessagesController < ApplicationController
before_action :authenticate_user!
def new
@chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]
end
def create
recipients = User.where(id: params['recipients'])
conversation = current_user.send_message(recipients, params[:message][:body], params[:message][:subject]).conversation
flash[:success] = "Message has been sent!"
redirect_to conversation_path(conversation)
end
end
答案 0 :(得分:1)
我认为没有一种简单的方法可以将NameID.innerHTML
嵌入到ERB中。所以我建议使用一些自定义的jQuery代替。首先,在您的链接中添加ID:
<%= link_to 'Send message', new_message_path(to: people.id), id: 'sendMessage', class: 'btn btn-default btn-sm' %>
然后在脚本中使用jQuery:
$("#sendMessage").click(function(e){
e.preventDefault();
var nameId = $("#NameID_Div").html();
// Then just assign the proper URL of the new_message_path with the proper NameID
location.assign('/message/' + nameId + '/new');
});