Search code examples
javascriptruby-on-railsrubyformsmailboxer

Pre-fill form field with data from prior page in Rails


I recently added Mailboxer to my Rails app and have everything working well.

However, I want to be able to create a new message by clicking a "Message Me" button on a User's page and then have the recipient filled in already (with the User from the prior page) when the form for creating the message loads.

The particular field in question:

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

And for reference, recipients_options probably won't come into play in this scenario, but it is the list of all Users--which I use primarily when I'm creating a Message from anywhere but a User page--and is defined in my Messages helper

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

And my 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

I already have the link to the New Message form on each User page...

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

But I don't know how to pre-fill the recipient in the subsequent form.

Any suggestions for how would I go about this?


Solution

  • Change the link_to code to this:

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

    In messages#new action, add this code:

    def new
      @users = User.all
    end
    

    And, in message form, replace the select_tag with this:

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

    I made some changes in recipients select. You can use options_from_collection_for_select method to generate that options instead implement your own helper.

    Reference: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select