orberkov
orberkov

Reputation: 1165

Create Refile attachment from HTTpary on a Ruby model with mongo db

Building a mobile app with Rails backend, I would like to import the facebook profile picture from facebook to my own system using rails. The profile image is located at some url, and the pictures in my backend are being saved using Refile.

The ProfilePicture model:

class ProfilePicture
  include Mongoid::Document
  extend Refile::Mongoid::Attachment
  attachment :file, type: :image
  belongs_to :user

  field :created_at, type: String
  field :updated_at, type: String
end

The User model:

class User
  include Mongoid::Document

  field :created_at, type: String
  field :updated_at, type: String

  has_one :profile_picture
end

The code to set the Picture, using HTTParty:

@user = User.find_by(id: 1)
@picture_data = HTTParty.get("https://graph.facebook.com/me/picture", query: {
    access_token: access_token,
    type: "large"
})
pic = ProfilePicture.new(file: @picture_data.body)
@user.update(profile_picture: pic)

The profile picture is GETed, as I can see the data in the HTTP result. The DB result of the "Update" action above would be a new ProfilePicture record in the mongodb, with a reference to the user data, so that's OK too. So the only problem is, that the attachment is not being saved.

How do I save the attachement?

Upvotes: 0

Views: 105

Answers (1)

orberkov
orberkov

Reputation: 1165

The answer was that the image file being GETed from facebook was not a valid "image" type for the attachment. The change was to remove the type from the attachment property, like so:

class ProfilePicture
  include Mongoid::Document
  extend Refile::Mongoid::Attachment
  attachment :file
  belongs_to :user

  field :created_at, type: String
  field :updated_at, type: String
end

Upvotes: 0

Related Questions