Rails 3 中将 xml 转换为 ActiveRecord 对象的内置方法?
在 Rails 3 中,有没有一种方法可以从控制器中的 xml 生成 ActiveRecord 对象,而无需自己编写代码来显式解析它?例如,控制器可以接收 xml
<user>
<first_name>Bob</first_name>
<last_name>Smith</last_name>
</user>
并让它生成类似于 User.new(params[:user]) 的正确 User 对象吗?这是针对 api 的。
In Rails 3, is there a way to produce an ActiveRecord object from xml in a controller without writing code yourself to explicitly parse it? Say for example, could a controller receive xml like
<user>
<first_name>Bob</first_name>
<last_name>Smith</last_name>
</user>
and have it produce a proper User object similar to User.new(params[:user])? This is for an api.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以这样做:
更新
在覆盖时,您可以执行以下操作:
请注意,覆盖中最重要的行是
super(xml_data)
将谨慎调用ActiveRecord
模型的原始from_xml(xml_data)
。因此,您可以根据需要自定义其余部分,但如果您还想获得原始功能,则需要此行。
如果有不清楚的地方请告诉我。
Yes, you can do it like this:
Update
On overriding you can do something like this:
Please note that the most important line in the overriding is the
super(xml_data)
which will take care on calling the originalfrom_xml(xml_data)
of theActiveRecord
model.So you can customize the rest as needed, but this line is neede if you want to get the original functionality as well.
Let me know if something is not clear.
我创建了一个 gem,xml_active 可以帮助您解决此问题,而无需编写大量代码。您可以在 https://rubygems.org/gems/xml_active 上查看。
要让它创建一个具有关联的对象,只需执行以下操作:
您还可以使用 xml_active 从 xml 创建许多对象以及关联。还有更多功能,但可能不在本答案的范围内。您可以在宝石的主页上查看它们。
更新
xml_active 现已正式退役,开发现在集中在 data_active 上(请参阅 https://github.com/michael -harrison/data_active),它具有 xml_active 的功能,但在未来的版本中我将努力支持其他格式
I've created a gem, xml_active that might help you with this without having to write a lot of code. You can check it out at https://rubygems.org/gems/xml_active.
To get it to create one object with associations just do the following:
You can also get xml_active to create many objects from xml along with associations. There are more features but probably not in the scope of this answer. You can check them out on the home page for the gem.
UPDATE
xml_active has now been officially retired and development is now focused on data_active (see https://github.com/michael-harrison/data_active) which has the functionality of xml_active but in future releases I will be working to support other formats