我有一个相对简单的Rails应用程序,该应用程序具有包含照片的嵌套参数的形式。看起来像这样:

class List < ActiveRecord::Base
  has_many :list_items
  has_many :people, through: list_items
end

class ListItem < ActiveRecord::Base
  belongs_to :list
  belongs_to :person, autosave: true

  has_attached_file :picture,
    :storage => :s3,
    :bucket => 'myfreebielist',
    :s3_credentials => {
      :access_key_id => ENV['S3_KEY'],
      :secret_access_key => ENV['S3_SECRET']
    }


  def autosave_associated_records_for_person
    if new_person = Person.find_by_name(Person.name) then
      self.person = new_person
    else
      self.person.save!
    end
  end
end

class Person < ActiveRecord::Base
  has_many :list_items
end


我设置了一个新的测试表单,以确保一切正常,并且一切都很好:

<%= form_for @list do |f| %>
  List name: <%= f.text_field :name %><br/>
  <%= f.fields_for :list_items do |lif| %>
    <%= lif.fields_for :person do |pif| %>
    Person name: <%= pif.text_field :name %>
    <% end %>
    Picture: <%= lif.file_field :picture %>
    <br/>
  <% end %>
  <%= f.submit %>
<% end %>


好的,所以我希望能够发布一个新列表,其中包含列表项(及其相关的图片)以及该列表项的人员。我有正在目标C中测试的代码:

NSMutableDictionary *listParams = [NSMutableDictionary dictionary];
[listParams setValue:@"Test One" forKey:@"name"];

NSMutableDictionary *listItems = [NSMutableDictionary dictionary];

// Generate each list item -- a person and a photo.
NSDictionary *person1 = [NSDictionary dictionaryWithKeysAndObjects:@"name", @"John Smith", nil];
NSDictionary *listItem1 = [NSDictionary dictionaryWithKeysAndObjects:@"person_attributes", person1, nil];
[listItems setValue:listItem1 forKey:@"0"];
[listParams setValue:listItems forKey:@"list_items_attributes"];

NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setValue:listParams forKey:@"list"];

[[RKClient sharedClient] post:@"/lists" params:params delegate:self];


在没有图片的情况下,这也可以正常工作。

现在,我知道应该使用RKParams代替NSDictionary来处理这种类型的请求,但是当我使用RKParams进行发布时,各种奇怪的事情都会出现。 -键周围有许多\n换行符,空格和其他内容。我尝试使用带有附件的RKParams作为person1的一部分,但它似乎只是发送对象RKParams对象名称的字符串表示形式。

我觉得我是如此接近,如此亲近,但是我已经好几个小时都对此表示反对。任何帮助,将不胜感激。

环境:Xcode 4.3,Rails 3.2.1。

最佳答案

答案是:JSON。我必须调整服务器以支持JSON,这是我一开始应该做的事情。这就是所有空格和\n的含义。自我注意:无论您有多积极性,都不要通宵编程。

10-01 16:17