【发布时间】:2011-11-13 12:03:24
【问题描述】:
如何从字符串参数中提取和保存数组?我正在尝试转换字符串 before_create 但这不起作用。当我评论 before_create :waypoints Mongoid 抛出错误时:
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"nehoT1fnza/ZW4XB4v27uZsfFjjOu/ucIhzMmMKgWPo=",
"trip"=>{
"title"=>"test",
"description"=>"test",
"waypoints"=>"[[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003]]"
}
}
Completed 500 Internal Server Error in 1ms
Mongoid::Errors::InvalidType (Field was defined as a(n) Array, but received a String with the value "[[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003]]".):
编辑感谢您的帮助,现在可以使用,但我不知道以下方法是否好。我删除 before_create 并将参数名称从 waypoints 更改为 waypoints_s 并将 def waypoints 更改为 def waypoints_s:
#Parameters:
#"waypoints"=>"[[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003]]"
"waypoints_s"=>"[[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003]]"
class Trip
include Mongoid::Document
field :title, :type => String
field :description, :type => String
field :waypoints, :type => Array
#before_create :waypoints
#def waypoints=(arg)
def waypoints_s=(arg)
if (arg.is_a? Array)
#@waypoints = arg
self.waypoints = arg
elsif (arg.is_a? String)
#@waypoints = arg.split(',')
self.waypoints = JSON.parse(arg)
else
return false
end
end
end
class TripsController < ApplicationController
def create
@trip = Trip.create(params[:trip])
@trip.save
end
end
【问题讨论】:
标签: ruby arrays ruby-on-rails-3 mongoid