【问题标题】:Creating multiple resources in a single RESTful POST in rails在 Rails 中的单个 RESTful POST 中创建多个资源
【发布时间】:2011-01-15 06:02:56
【问题描述】:

我正在 Rails 中创建一个 API,以向我正在开发的 iPhone 应用程序公开。我知道通常您在发布到 Rails 中控制器的创建操作时只创建一个资源。但是,我不确定一次创建许多资源的最佳方式。在单个 POST 中发布包含多个要创建的相同类型的资源的 JSON/XML 是否可以接受?

例如,创建一条消息,然后添加许多收件人。消息本身有一个模型,然后是属于该消息的收件人的模型。我通过发布到 /messages 来创建消息,但是如果我有 50 个收件人要添加到该消息中怎么办?向 /messages/1/recipients 发送 50 个单独的 POST 似乎过多且浪费。解决此问题的最佳方法是什么?

总的来说,我是 Rails 和 RESTful 应用程序的新手,非常感谢任何帮助。

【问题讨论】:

    标签: ruby-on-rails rest post resources


    【解决方案1】:

    您可以为此使用accepts_nested_attributes_for。在您的父模型中 - 您定义您的 has_many 关联 - 您将添加 accepts_nested_attributes_for 给它相同的关联名称。很像这样:

    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_forfields_for(当您转到new 页面时,您只需记住在您的has_many 集合中至少构建一个实例)。

    如需更多(更好的)示例,请watch this Railscast

    【讨论】:

    【解决方案2】:

    如果您发布 XML 数据,您还需要包含 type="array"。这是一个例子:

    <message>
      <recipients_attributes type="array">
         <recipient>
           <name>Some Name</name>
           <email>example@example.com</email>
         </recipient>
         <recipient>
           <name>Some Name 2</name>
           <email>example2@example.com</email>
         </recipient>
      <recipients_attributes>
    </message>
    

    如果你不这样做,你会得到像“undefined method `stringify_keys' for Array”和“can't convert String into Integer”之类的错误,具体取决于你的 Rails 版本。这些来自 active_record/nested_attributes.rb。

    【讨论】:

      猜你喜欢
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多