1

最近Mailboxer、Rails アプリに追加したところ、すべてがうまく機能しています。

ただし、ユーザーのページの「メッセージを送信」ボタンをクリックして新しいメッセージを作成し、メッセージを作成するためのフォームがロードされたときに、受信者が (前のページのユーザーで) 既に入力されているようにしたいと考えています。

問題の特定のフィールド:

<%= select_tag 'recipients', recipients_options, multiple: true, class: 'new_message_recipients_field' %>

参考までにrecipients_options、このシナリオではおそらく役に立たないでしょうが、これはすべてのユーザーのリストです。これは主に、ユーザー ページ以外の場所からメッセージを作成するときに使用し、メッセージで定義されています。ヘルパー

def recipients_options
  s = ''
  User.all.each do |user|
    s << "<option value='#{user.id}'>#{user.first_name} #{user.last_name}</option>"
  end
  s.html_safe
end

そして私のmessages_controller.rb

def new
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

各ユーザーページに新規メッセージフォームへのリンクが既にあります...

<%= link_to 'Message me', new_message_path %>

しかし、後続のフォームで受信者を事前に入力する方法がわかりません。

これについてどうすればいいですか?

4

2 に答える 2

3

link_toコードを次のように変更します。

<%= link_to 'Message me', new_message_path(recipient_id: @user.id) %>

実際に、次messages#newのコードを追加します。

def new
  @users = User.all
end

そして、メッセージ フォームで、select_tag を次のように置き換えます。

<%= select_tag 'recipients', options_from_collection_for_select(@users, :id, :first_name, params[:recipient_id]), multiple: true, class: 'new_message_recipients_field' %>

受信者の選択にいくつかの変更を加えました。options_from_collection_for_select独自のヘルパーを実装する代わりに、メソッドを使用してそのオプションを生成できます。

参照: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select

于 2015-01-19T21:39:18.120 に答える
0

私は Mailboxer を使用しており、Listing ページから販売者に連絡できます。

ユーザーがリスト ページの [販売者に連絡] ボタンをクリックすると、次のページで To: フォームに販売者の名前が入力されます。

メッセージコントローラーと同じ Create メソッドがあります。しかし、NEWメソッドではこれがあります:

MessageController

  def new
    @chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]
  end

リスティング ページの連絡先ボタン:

</p>
  <strong>Contact Seller about "<%= @listing.title %>"</strong></br>
  <%= link_to "Send message to #{@listing.user.name}", new_message_path(to: @listing.user.id), class: 'btn btn-default btn-sm' %>
<p>

新しいメッセージ フォーム:

<%= form_tag messages_path, method: :post do %>
  <div class="form-group">
    <%= label_tag 'message[subject]', 'Subject' %>
    <%= text_field_tag 'message[subject]', nil, class: 'form-control', required: true %>
  </div>

  <div class="form-group">
    <%= label_tag 'message[body]', 'Message' %>
    <%= text_area_tag 'message[body]', nil, cols: 3, class: 'form-control', required: true %>
  </div>

  <div class="form-group">
    <%= label_tag 'recipients', 'Choose recipients' %>
    <%= select_tag 'recipients', recipients_options(@chosen_recipient), multiple: true, class: 'form-control chosen-it' %>
  </div>

  <%= submit_tag 'Send', class: 'btn btn-primary' %>
<% end %>

お役に立てれば!

于 2015-07-30T22:12:08.893 に答える