将数组中的项目保存到活动记录中

时间:2015-11-06 13:50:29

标签: ruby-on-rails

我有一个如下所示的数组:

NSURL *url = [[NSURL alloc]initWithString:self.productName];
            dispatch_queue_t imageFetchQ = dispatch_queue_create("image fetcher", NULL);
            dispatch_async(imageFetchQ, ^{
                NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
                UIImage *image = [[UIImage alloc]initWithData:imageData];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.productImage.image=image;
                    }
                });

            }); 

现在我试图像这样保存它:

[{"id"=>"2", "reply"=>"ok"}, {"id"=>"3", "reply"=>"ok"}, {"id"=>"4", "reply"=>"ok"}, {"id"=>"5"}, {"id"=>"6", "reply"=>"2"}]

但结果是

current_user.answers.transaction do

  success = params[:answers].map(&:save)
  unless sucess.all?
    errored = params[:answers].select { |b| !b.errors.blank? }
    raise ActiveRecord::Rollback
  end

end

有人知道如何保存每件物品吗?

undefined method `save' for {"id"=>"2", "reply"=>"ok"}:ActionController::Parameters

1 个答案:

答案 0 :(得分:0)

是的,只需发送一个块......所以你可以尝试:

current_user.answers.transaction do
  success = params[:answers].map do |hash|
    object = Model.new(hash)
    object.save
  end
  unless success.all?
    errored = params[:answers].select { |b| !b.errors.blank? }
    raise ActiveRecord::Rollback
  end
end

意识到Model需要是您尝试使用实例化对象的模型的名称。

但是,只有当您制作新对象时才会这样做,而您通常不会设置id属性

current_user.answers.transaction do
  success = params[:answers].map do |hash|
    object = Model.find(hash["id"])
    object.update_attributes(hash)
  end
  unless success.all?
    errored = params[:answers].select { |b| !b.errors.blank? }
    raise ActiveRecord::Rollback
  end
end

希望这有帮助