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

引用文字をエスケープするためにスラッシュが追加されています。これは、配列を取得して文字列にする場合は正常であり、これは舞台裏で行われています。エスケープ文字の詳細については、このウィキペディアの記事を参照してください。

複数の値を 1 つのフィールドに保存したい場合は (別のテーブルに保存してから保存することを検討してください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\"]"

于 2013-10-27T16:07:10.257 に答える