Rails creating bulk objects via a web service
I'm writing a rails web-hooks service consumer that receives bulk objects in nested XML and need to save certain fields in each node. When the XML data hits my create action in my HooksController, the XML is automatically converted into a hash that looks like this.
Parameters: {"Events"=>{"RecordSet"=>{"Record"=>[{"SENDER_LAST_NAME"=>"Smith",
"SENDER_MIDDLE_NAME"=>"S.", "EVENT_ID"=>"3904", "SENDER_FIRST_NAME"=>"John",
"EVENT_TYPE"=>"Contact", "SENDER_MSISDN"=>"0723xxxxxx", "EVENT_DATE"=>"2011-05-31"},
{"SENDER_LAST_NAME"=>"Simiyu", "SENDER_MIDDLE_NAME"=>"N.",
"EVENT_ID"=>"2447", "SENDER_FIRST_NAME"=>"Steve", "EVENT_TYPE"=>"Tag",
"SENDER_MSISDN"=>"0720xxxxxxx", "EVENT_DATE"=>"2011-05-31"}]}, "xmlns"=>""}}
I don't want to store all the fields from each object since my ExternalEvents model which corresponds to Events in the hash doesn't have all the fields in the hash. Also I want to match the field SENDER_MSISDN to registered users MSISDN before开发者_JAVA百科 saving. Normally I'd use Nokogiri to parse the XML and thereafter create the Model objects in a loop, but I can't do this since rails automagically converts it to a hash. I have no way of changing the structure of the XML coming in.I have tried looking for a clue on how to go about this unsuccessfully.
I'm on the verge of ripping my hair off on this one.
You'll need to write some manual code to do this. How about something like:
params["Events"]["RecordSet"]["Record"].each do |h|
ExternalEvent.create(h.merge({ :MSISDN => h["SENDER_MSISDN"] }))
end
If you need to remove certain fields then you can use the delete_if
method for Hash
. For example:
h.merge(..).delete_if {|key, value| [ "DONT_WANT", "THIS"].include?(key) }
external_event = ExternalEvents.new(params[:Events][:RecordSet][:Record])
This should create a new instance, with attributes matching the key-value pairs in the Record hash, assuming your field names match.
Use a model validation on SENDER_MSISDN and put a foreign key constraint on the external_events.SENDER_MSISDN column.
精彩评论