Rails 通过 Web 服务创建批量对象
我正在编写一个 Rails Web-hooks 服务使用者,它接收嵌套 XML 中的批量对象,并且需要在每个节点中保存某些字段。当 XML 数据命中 HooksController 中的创建操作时,XML 会自动转换为如下所示的哈希值。
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"=>""}}
我不想存储每个对象的所有字段,因为与哈希中的事件相对应的外部事件模型没有哈希中的所有字段。另外,我想在保存之前将字段 SENDER_MSISDN 与注册用户 MSISDN 进行匹配。通常我会使用 Nokogiri 解析 XML,然后在循环中创建模型对象,但我不能这样做,因为 Rails 会自动将其转换为哈希。我无法更改传入的 XML 的结构。我尝试寻找有关如何解决此问题的线索,但未成功。
我差点就为了这个把头发扯下来了。
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 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要编写一些手动代码来执行此操作。怎么样:
如果您需要删除某些字段,那么您可以使用
Hash
的delete_if
方法。例如:You'll need to write some manual code to do this. How about something like:
If you need to remove certain fields then you can use the
delete_if
method forHash
. For example:这应该创建一个新实例,其属性与记录哈希中的键值对匹配,假设您的字段名称匹配。
对 SENDER_MSISDN 使用模型验证,并在 external_events.SENDER_MSISDN 列上放置外键约束。
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.