如何以Rails 4.2的形式提交字符串数组

时间:2015-07-27 01:45:07

标签: arrays ruby postgresql rails-postgresql ruby-on-rails-4.2

我有一个带有字符串数组属性收件人的消息模型。这是我的messages_controller.rb看起来像

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

_fields.html.erb看起来像这样:

<%= 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" %>

问题是如此保存“数组”

["recipient_1, recipient_2"]

而不是

["recipient_1", "recipient_2"]

我希望能够检索收件人[0] = recipient_1而不是收件人[0] =整个数组 它可能很简单,但我找不到修复方法。 所有投入都赞赏。 感谢

2 个答案:

答案 0 :(得分:2)

返回单个字符串,因为输入是文本字段。如果你想为此使用一个文本字段,那么只需要输入将以逗号分隔并拆分输入:

@message.recipients = params[:message][:recipients].split(',')

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

答案 1 :(得分:0)

通常对于permit,您传递一组:符号。这些键只能表示标量值。但是数组由空数组表示不同。

试试这个:

def create_params
    params.require(:message).permit(:object,
                                    :content,
                                    :attachments,
                                    recipients: [])
end

表格中的字段:

<%= f.text_field_tag "recipients[]", :recipients, multiple: true, class: "form-control" %>