我有一个相对简单的 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 %>
好的,所以我希望能够发布一个新列表,其中包含列表项(及其相关图片图像)以及该列表项的人员。我在 Objective 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
rails 端出现了各种奇怪的东西——许多 \n
换行符、空格和键周围的东西。我尝试使用带有附件的 RKParams
作为 person1
的一部分,但它似乎只是发送对象 RKParams 对象名称的字符串表示形式。
我觉得我是如此,如此接近,但我几个小时以来一直在反对这个问题。任何帮助将不胜感激。
环境:Xcode 4.3,Rails 3.2.1。
最佳答案
答案是:JSON。我必须调整服务器以支持 JSON,这是我一开始就应该做的事情。这就是所有空格和 \n
的意义所在。 self 提醒:无论你多么有动力,都不要通宵编程。
关于ruby-on-rails - RestKit 和 RKParams 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9481966/