在Rails的单个RESTful POST中创建多个资源 [英] Creating multiple resources in a single RESTful POST in rails
问题描述
我正在Rails中创建一个API,以向正在使用的iPhone应用程序公开.据我了解,通常只有在发布到Rails中控制器的create操作时才创建单个资源.但是,我不确定一次创建多个资源的最佳方法.在单个POST中发布包含要创建的相同类型的多个资源的JSON/XML是否可以接受?
I'm creating an API in rails to expose to an iPhone app that I'm working on. I understand that usually you only create a single resource when posting to the create action of a controller in Rails. However, I'm not sure the best way to go about creating many resources at once. Is it acceptable to post JSON/XML containing multiple resources to be created of the same type in a single POST?
例如,创建一条消息,然后添加许多收件人.有一个消息本身的模型,然后有一个属于该消息的收件人的模型.我通过发布到/messages创建消息,但是如果我有50个收件人要添加到该消息中怎么办?对/messages/1/recipients进行50个单独的POST似乎过于浪费.最好的方法是什么?
For example, creating a message and then adding many recipients. There is a model for the message itself, and then a model for a recipients that belongs to the message. I create the message by posting to /messages, but then what if I have 50 recipients to add to that message? Making 50 separate POSTs to /messages/1/recipients seems excessive and wasteful. What is the best way to go about this?
我一般是Rails和RESTful应用程序的新手,非常感谢您的帮助.
I'm new to Rails and RESTful apps in general and very much appreciate any help.
推荐答案
您可以为此使用accepts_nested_attributes_for
.在父模型(定义has_many
关联)中,您要添加accepts_nested_attributes_for
,并为其赋予相同的关联名称.很像这样:
You could use accepts_nested_attributes_for
for this. In your parent model – where you define your has_many
association – you'd add the accepts_nested_attributes_for
giving it the same association name. Much like this:
class Message < ActiveRecord::Base
has_many :recipients
accepts_nested_attributes_for :recipients
end
class Recipient < ActiveRecord::Base
belongs_to :message
end
然后,以邮件的形式,您将为收件人指定一堆字段,它们的名称类似于message[recipients_attributes][][name]
和message[recipients_attributes][][email]
.或者,您可以使用form_for
和fields_for
(当您进入new
页面时,只需要记住在has_many集合中至少构建一个实例)即可.
Then, in your message's form, you'd have a bunch of fields for the recipients named something like message[recipients_attributes][][name]
and message[recipients_attributes][][email]
. Or you could use form_for
and fields_for
(you just have to remember to build at least one instance in your has_many collection when you go to the new
page).
有关更多(更好)的示例,请观看此Railscast .
For more (and better) examples, watch this Railscast.
这篇关于在Rails的单个RESTful POST中创建多个资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!