0

I want to implement functionality where User A can send a message to User B. Say User A is viewing User B's profile and clicks on the Send Message link, how can I make sure that only User B will receive the message. In other words in the Create action how can I capture User B? I am able to capture User B in the new action but not in the create action. Here is what I have so far:

class MessagesController < ApplicationController

  def new
      @message = Message.new
      @recipient = User.find_by_identifier!(params[:id])
  end

  def create
      @message = Message.new(params[:message])
      @message.recipient = @recipient
      @message.sender = current_user
      if @message.save
        flash[:notice] = "Message has been sent"
        redirect_to messages_path(:mailbox=>:sent)
      else
        render :action => :new
      end
  end
end

So the Send Message link passes in the params of User B for the new action. So @recipient in the new action is User B and I am able to display User B's name and picture. But @recipient is nil in the create action. How can I ensure that @recipient in the create action is User B?

4

2 に答える 2

1

コントローラーのインスタンス変数は、1 つのリクエストに対してのみ有効です。リクエスト中にそれ以上@recipient設定されることはありません。newcreate

だからもう一度見てください!:idが HTTP パラメータにまだ存在することを確認し、そのまま@message.recipient = User.find(params[:id]).

于 2013-04-22T10:17:59.787 に答える
1

メッセージ送信フォームに、受信者のユーザー ID である隠しフィールドを追加します。

あなたのフォームで:

<%= f.hidden_field :recipient_id, :value => @recipient.id %> 

このようにして、パラメーターに受信者が含まれ、受信者情報を使用して新しいメッセージを作成します。

また、作成アクションのルートが何であるかにも依存します。recepient_idルートで利用可能な場合は、newアクションで行ったように再度使用してください。

于 2013-04-22T10:18:10.457 に答える