Rails Carrierwave upload multiple files undefined method `[]' for nil:NilClass

Deadly 提交于 2019-12-11 06:11:54

问题


someone please can clarify why this

undefined method `[]' for nil:NilClass

is happening on upload files with rails, carrierwave and react?

the rest of the code are very standard, so in the logs on upload image always the image attribute from post_attachments shows blank.

i suspected that the problem is with the rails loop over the post_attachments on post create, what do you guys think?

and i changed to

 params[:post_attachments].each do |image|
    img = PostAttachment.new
    img.image = image
    @post.post_attachments << img
  end 

and still showing the error.

so please, someone has any idea why this with carrierwave and react?

here is post controller

  def create


    @post = current_user.posts.build(post_params)


    if @post.save
      #unless params[:post_attachments].nil?
        params[:post_attachments]['image'].each do |a|
          @post_attachment = @post.post_attachments.create!(:image => a, :post_id => @post.id)

      #end


    end

    render json: "Posted successfully", status: 201
    else
      render json: @post.errors, status: :unprocessable_entity
    end
  end

and the react

  async sendImage(forma) {
    let self = this;
    let errs = 0;
    let auth_token = await AsyncStorage.getItem(AUTH_TOKEN);

    try {
      let response = await fetch("https://localhost:3000/posts", {
        method: "POST",
        headers: {
          Accept: "application/json",

          //"Content-Type": "multipart/form-data",
          Access: auth_token
        },
        body: forma
      });
      let res = await response.text();
      if (response.status >= 200 && response.status < 300) {
      } else {
        //Handle errors
        let error = res;
        throw error;
      }
    } catch (errors) {
      //errors are in JSON form so we must parse them first.
      let formErrors = JSON.parse(errors);
      //We will store all the errors in the array.
      let errorsArray = [];
      for (var key in formErrors) {
        //If array is bigger than one we need to split it.
        if (formErrors[key].length > 1) {
          formErrors[key].map(error => errorsArray.push(`${key} ${error}`));
        } else {
          errorsArray.push(`${key} ${formErrors[key]}`);
        }
      }
      this.setState({ errors: errorsArray });
      //this.setState({showProgress: false});
    }
  }

  async uploadImage() {
    const { params } = this.props.navigation.state;
    let image = params ? params.image : null;
    let photos = params ? params.photos : [];

    var self = this;
    let forma = new FormData();

    forma.append("post[title]", String(this.state.title));
    forma.append("post[body]", String(this.state.body));

    forma.append("post[post_attachments][image][]", 'teste');

    for (let i = 0; i < photos.length; ++i) {
      await fs
        .readFile(photos[i], "base64")
        .then(async blob => {
          //forma.append("post[post_attachments][image][]", 'teste');

        .catch(error => {
          console.log("loop err", error);
        });
    }

    self.sendImage(forma);
  }

log screenshot


回答1:


params are like this: -

paramaters: {"post" = > .... "post_attachments" => {"image" => ["test"]}}

So image_params should be like this -

image_params = params[:post][:post_attachments][:image]

And

  unless image_params.blank?
    image_params.each do |image|
      img = PostAttachment.new
      img.image = image
      @post.post_attachments << img
    end 
  end


来源:https://stackoverflow.com/questions/53577345/rails-carrierwave-upload-multiple-files-undefined-method-for-nilnilclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!