0

我有一个如下所示的控制器方法。但是,schedule = params[:message][:schedule]接受这样的输入["","2"]并作为字符串存储在 MySQL 数据库中。

Schedule.create(execution_time: scheduled_time, lists: "lists", message_id: @message.id, user_id: current_user.id)存储的值是数据库"--- \n- \"58\"\n- \"\"\n"时,Schedule.create(execution_time: scheduled_time, lists: "#{lists}", message_id: @message.id, user_id: current_user.id)然后存储的值是这样"[\"34\", \"\"]"的,但所需的值是["34", ""]

控制器方法如下;

def create
  @lists = current_user.lists.all
  @message = Message.new(params[:message])
  lists = params[:message][:lists]
  schedule = params[:message][:schedule]

  if @message.save
    if schedule.blank?
      MessageWorker.perform_async(@message.id, lists, current_user.id)
    else
      scheduled_time = DateTime.strptime(schedule,"%m/%d/%Y %H:%M %p %z").to_datetime.utc.strftime("%Y-%m-%d %H:%M:%S")
      Schedule.create(execution_time: scheduled_time, lists: "#{lists}", message_id: @message.id, user_id: current_user.id)
    end
    redirect_to new_message_path, notice: 'Message was successfully added to the queue.'

  else
    render action: "new"
    flash[:notice] = "Messages Not Sent"
end

为什么存储值中有斜杠?先感谢您。

4

1 回答 1

2

添加斜杠以转义引号字符。这在获取数组并将其变为字符串时是正常的,这就是幕后发生的事情。有关转义字符的更多信息,请参阅此 Wikipedia 文章

如果你真的想在一个字段中存储多个值(考虑存储在单独的表中,然后可以JOIN'd to),那么要么将它们存储为 JSON 格式,要么作为逗号分隔值。这两种方法都要求您在从数据库中读取存储的值时对其进行解析。

JSON:

lists = JSON.generate(params[:message][:lists]) # an array such as ["1", "2"], converted to JSON format
=> "[\"1\",\"2\"]" # it's a string, with quotes escapted. Store this in the database.

# then you can parse it to make it an array again
JSON.parse(lists)
=> ["1", "2"]

逗号分隔值:

lists = params[:message][:lists].join(",") # assuming params[:message][:lists] is an array
=> "1,2" # A string with each value from the array separated by a comma. Store this in database

# then when you read that value from database
lists.split(",")
=> ["1", "2"] # back in array format

您正在获取一个数组,然后将其存储为字符串。转换为此格式时,斜杠是必需的。要将字符串恢复为数组格式,您需要解析字符串 - 这将“删除”斜杠。["1", "2"]确保您了解和之间的区别"[\"1\", \"2\"]"

于 2013-10-27T16:07:10.257 回答