我有一个如下所示的 Controller 方法。但是,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”,“”]
。
Controller 方法如下;
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
为什么存储的值中要加斜杠? 预先感谢您。
最佳答案
添加斜杠是为了转义引号字符。当获取数组并将其设为字符串时,这是正常的,这是幕后发生的事情。请参阅this Wikipedia article有关转义字符的更多信息。
如果您确实想在一个字段中存储多个值(考虑存储在单独的表中,然后可以进行JOIN
连接),那么可以将它们存储为 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\"]"
关于mysql - Ruby 模型将 Controller 值存储在 MYSQL 中并添加字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19619674/