arraysrubypostgresqlrails-postgresqlruby-on-rails-4.2

How to submit a string array in a form Rails 4.2


I have a model message with a string array attribute recipients. Here's what my messages_controller.rb looks like:

def new
  @message = Message.new
  @message.attachments = params[:attachments]
end
def create
  @message = Message.new(create_params)
  @message.user_id = current_user.id
  @message.attachments = params[:message][:attachments]
  @message.recipients = params[:message][:recipients]
  save_message or render 'new'
end
private
  def create_params
    params.require(:message).permit(:object, :content,
                                  :recipients,
                                  :attachments)
  end

And the _fields.html.erb looks like this:

<%= render 'shared/error_messages', object: f.object %>
<%= f.label :object %>
<%= f.text_field :object, class: "form-control" %>
<%= f.label :recipients %>
<%= f.text_field :recipients, multiple: true, class: "form-control" %>
<%= f.label :attachments %><br>
<%= f.file_field :attachments, multiple: true, class: 'form-control' %><br />
<%= f.label :content %>
<%= f.text_area :content, class: "form-control" %>

The problem is that it saves the recipients array like this:

["recipient_1, recipient_2"]

instead of

["recipient_1", "recipient_2"]

I want to be able to retrieve recipient[0] = recipient_1 and not recipient[0] = whole array.

It's probably something simple, but I can't find the fix. All inputs appreciated. Thanks


Solution

  • It is returning a single string because the input is a text field. If you want to utilize a text field for this then just expect that the input will be comma-separated and split the input:

    @message.recipients = params[:message][:recipients].split(',')
    
    # or, if it's wrapped in an array
    # @message.recipients = params[:message][:recipients][0].split(',')