2016-09-12 11 views
0

私はdeviseモデルUserを生成しました。私は会話コントローラも持っています。ログインしたユーザーを除くすべてのユーザーを表示していますが、user1とuser2の間に新しい会話を作成しようとしていますが、会話コントローラのインデックスメソッドにリダイレクトされます。私はこのリンクから、あるコントローラから別のコントローラへのポストを作ることが悪い考えであることを理解した。Rails: How to POST internally to another controller action?あるコントローラのインデックスメソッドから他のコントローラのインデックスメソッドにデータを渡して

私はまた、ユーザコントローラ内でsend_messageメソッドを作成し、それをルート内の投稿として定義しようとしましたが、ユーザコントローラのshowメソッドにリダイレクトされます。

これを行うにはどうすればよいですか?

class UsersController < ApplicationController 
    before_action :authenticate_user! 

    def index 
    @users = User.where.not(id: current_user.id) 
    end 

    def send_message 
    # @conversation = Conversation.new(conversation_params) 
    # if @conversation.save 
    # 
    # end 
    end 

end 

index.html.erb

<div class="col-xs-12 col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> 
<h1> User's index </h1> 

<table class="table table-bordered table-hover"> 
    <thead> 
    <tr> 
     <th>Email</th> 
     <th>Created</th> 
     <th>Actions</th> 
    </tr> 
    </thead> 
    <tbody> 
    <% @users.each do |user| %> 
     <tr> 
     <td><%= user.email %></td> 
     <td><%= time_ago_in_words(user.created_at) %> ago</td> 
     <td> 
      <div class="btn-group"> 
      <%= link_to 'Send', conversations_path(sender_id: current_user.id, recipient_id: user.id) %> 
      </div> 
     </td> 
     </tr> 
    <% end %> 
    </tbody> 
</table> 


</div> 

編集:デフォルトでは

private 
    def conversation_params 
    params.require(:conversation).permit(:sender_id, :recipient_id) 
    end 


<ActionController::Parameters {"_method"=>"post", "authenticity_token"=>"394MDmcVVelccU//8ISYeqmk146exYc6G7SrrAhbCA/yQ/K8KTpSn/0EkXlZ4hB/g==", "recipient_id"=>"1", "sender_id"=>"3", "controller"=>"conversations", "action"=>"create"} permitted: false> 

答えて

0

link_toヘルパーはGETリクエスト送信します。オプションにmethod: :postを追加することでそれを行うことができます。

<%= link_to 'Send', path, method: :post %> 
+0

ありがとうございます。あなたが正しいです。どのように私はそれを考えていないのか分かりません。しかしこれは正しい方法ですか?コントローラ間にパラメータを渡すべきではないというリンクを投稿したので、それとも他に何かを指しているのでしょうか? –

+0

あなたはコントローラ間でパスパラメータを必要としません:) ConversationsController#create action(conversations_path)にリクエストを送る必要があります –

+0

paramsはcreateメソッドに行きますが、conversations_params.permitは 'paramが存在しないか、 :会話 '。プライベートメソッドと私が送信しているものを更新しました。私は新しい会話を送るべきですか? –

0

conversations_pathではなくnew_converstion_pathにリダイレクトできます。そして、リンクは、デフォルトでPOSTリクエストではなくGETを送信します。

+0

ありがとう。 Sergeiが 'method::post'で言ったように更新し、現在は動作しています。 –

関連する問題