我有一个如下所示的控制器方法。但是,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
为什么存储值中添加了斜杠?提前谢谢你。
添加斜杠以转义引号字符。当获取数组并将其设置为字符串时,这是正常的,这就是幕后发生的事情。有关转义字符的更多信息,请参阅此维基百科文章。
如果您确实想在一个字段中存储多个值(考虑存储在单独的表中,然后可以JOIN
到),那么将它们以 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"]"
之间的区别