2011-11-13 60 views
0

如何從字符串參數中提取並保存數組?我想轉換字符串beafore_create,但這不起作用。當我評論before_create:航點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]]".): 

編輯感謝您的幫助,現在它工作,但我不知道是不是下面的方法是很好的。我從航點waypoints_s和DEF航點刪除before_create和更改參數名稱變形點焊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 

回答

2

分析字符串作爲JSON對象:

require 'json' 

waypoints = "[[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003]]" 
JSON.parse(waypoints) 

=> [[52.40637, 16.92517], [52.40601, 16.925040000000003], [52.405750000000005, 16.92493], [52.40514, 16.92463], [52.404320000000006, 16.924200000000003]] 
+0

它在控制檯中運行良好,但在befor_create方法欄中忽略它並保存所有沒有航點的數據。 – leon

1

您需要使用連載http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-serialize

該方法通過YAML格式序列化的對象數據庫(假設只是具有某種格式的文本)。

class Trip < ActiveRecord::Base 

    serialize :waypoints 

end 

trip = Trip.create(:waypoints => [[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003]]) 

Trip.find(trip.id).waypoints # => [[52.40637,16.92517],[52.40601,16.925040000000003],[52.405750000000005,16.92493],[52.40514,16.92463],[52.404320000000006,16.924200000000003]] 
+0

我發現,在Mongoid我可以存儲陣列的字段而不序列化。我的問題仍然存在,我認爲有些方法將路線點參數從字符串轉換爲數組或刪除引號? – leon

+0

serialize方法正在爲您進行轉換,您只是像使用通常的數組那樣使用航點。對於我來說,使用序列化是更簡潔的方式,然後使用例如json,因爲你不需要解析,轉換的東西。 – megas

相關問題