How to convert local image to ::Fae::Image object ?
webmix opened this issue · 5 comments
Hi,
I'm starting using FAE and I love it.
I would like to automatically create an image (instead of uploading it).
This image is a screenshot of a website.
Actually I got everything working fine, using webshot rubygem.
I got the screenshot taken and saved correctly.
Now I'm trying to set this image as a 'thumb' record of the object.
Here is what I got so far:
class Site < ApplicationRecord
include Fae::BaseModelConcern
has_fae_image :thumb
before_validation :take_screenshot
def fae_display_field
name
end
private
def take_screenshot
if !self.prod_url.nil?
time = Time.now.to_i
path = "#{Rails.root}/tmp/screenshots/#{self.name.parameterize}-#{time}-screenshot.png"
ws = Webshot::Screenshot.instance
screenshot = ws.capture self.prod_url, path, width: 640, height: 480
file = File.open(path)
self.thumb = file
end
end
end
This is not working, and return this error:
ActiveRecord::AssociationTypeMismatch in Admin::SitesController#update
::Fae::Image(#70288845055340) expected, got #<File:/xxx/xxx/tmp/screenshots/hello-1548759578-screenshot.png> which is an instance of File(#70288767517600)
Any idea?
Thanks
Try self.thumb.asset = file
Yup, self.thumb
is an instance of Fae::Image
, which uses Carrierwave to manage assets. self.thumb.asset
is the Carrierwave object. You can reference their documentation for manually uploading:
https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-%22Upload%22-from-a-local-file
thanks
I tried to create a seed like this:
def seed_image(file)
image = Rails.root.join( 'app', 'assets', 'images', 'slider', "#{file}" )
Pathname.new( image ).open()
end
slides = [
{
title: "Emagreca\nsua cabeça",
slide_image: "4.jpeg"
},
{
title: "Grupos\nde apoio",
slide_image: "1.jpeg"
},
{
title: "Mudamos\nvidas",
slide_image: "2.jpeg",
color: "#ffa544"
}
]
slides.each do |slide|
image = seed_image( slide[:slide_image] )
slide.delete(:slide_image)
slider = Slide.create!(slide)
slider.slide_image = image
slider.save!
end
================================================
rails aborted!
ActiveRecord::AssociationTypeMismatch: ::Fae::Image(#46999995913520) expected, got #<File
:/paulobuosi/app/assets/images/slider/4.jpeg> which is an instance of File(#46999969233780)
/box/gems/activerecord-5.2.3/lib/active_record/associations/association.rb:246:in raise_on_type_mismatch!' /box/gems/activerecord-5.2.3/lib/active_record/associations/has_one_association.rb:27:in
replace'
================================================
But I still have this error, I tried in a number of ways and still can not, if anyone has any idea I'm grateful.
thanks
@enzoglauber - it looks like you are trying to save a File object and it's expecting a Fae::Image object. The Fae::Image object is a Carrierwave file. Take a look around the web for docs on how to generate fixtures for Carrierwave file objects.
try slider.slide_image.asset = image