2015-07-11 48 views
0

我有一個鏈接需要用戶的id。這保存在名爲NameID的div中。控制器等都設置正確,但我需要做的就是能夠通過NameID.innerHTML(這是一個數字)作爲people.id代表的數字。我怎樣才能做到這一點?在erb中添加div的innerHTML

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'); 
}); 
+0

Abraar嗨。代碼不起作用。我認爲sendmessage輸出需要而不是people.id。 people.id僅被定義爲來自控制器的@peoples變量的循環的一部分。如果我可以把jQuery結果放到這裏,那麼我根本不需要使用people變量。我怎麼能把jQuery的輸出,以便它作爲to:參數的一部分傳遞? –