Попытка размещения / размещения объектов с аватаром / изображением из прямой загрузки React в Rails - PullRequest
0 голосов
/ 02 апреля 2019

Я новичок в React и Rails. У меня есть ActiveStorage с AWS S3 и Direct_Upload для чтения в Rails. В React я не уверен, как реализовать это в запросе Fetch при создании нового или обновлении пользователя с аватаром или постом с изображением. Я слышал о FormData, но не совсем ясно, как атрибуты 'user /' post 'попадают в бэкэнд вместе с прикрепленными' avatar 'или' image '.

Вот мои User и Sighting модели в рельсах:

class User < ApplicationRecord
    include Rails.application.routes.url_helpers

    has_secure_password
    has_one_attached :avatar

    has_many :sightings
    has_many :animals, through: :sightings
    has_many :comments, :as => :commentable, dependent: :destroy


  def avatar_filename
    self.avatar.filename.to_s if self.avatar.attached?
  end

  def avatar_attached?
    self.avatar.attached?
  end



  validates :username, uniqueness: true

  def attachment_url
    if self.attachment.attached?
      Rails.application.routes.url_helpers.rails_blob_url(self.attachement, only_path: false)
    else
      nil
    end
  end

end
class Sighting < ApplicationRecord

  has_one_attached :image

  belongs_to :user
  belongs_to :animal
  has_many :comments, :as => :commentable, dependent: :destroy

  def image_filename
    self.image.filename.to_s if self.image.attached?
  end

  def image_attached?
    self.image.attached?
  end


end

и я пытаюсь выполнить обычный запрос Fetch, например, в React:


signup = (name, username, password, passwordConfirmation) => {
    if (password === passwordConfirmation) {
      fetch('http://localhost:9000/api/v1/users', {
        method: "POST",
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify({
          name: name,
          username: username,
          password: password
        })
      })
      .then(res => res.json())
      .then((response) => {
        if (response.errors) {
          alert(response.errors)
        } else {
          localStorage.setItem("token", response.token) // "jwt" can be any name
          this.setState({
            currentUser: response.user
          })
          this.props.history.push(`/login`)
        }
      })
    } else {
        alert("Passwords do not match!!")
    };
  };





How do I send avatar/image uploaded by user?
...