ruby

Render files and images for Rails 5 api only

Posted on

I had built a rails 5 api only app. By installing the app only version of rails, I lost the view layer of rails. No app/assets, or public files.

This is of course the intended design for an api application but my projects also needed to reference locally stored images. How to overcome?

Example: I need to fetch http://mysite/images/image5.jpg

Solution:

#config/routes.rb . #add a route

get ‘images/:id’, :to => ‘images#show’

#app/controllers/images_controller.rb #create this file, make class ImagesController,

#add method below

def show
id = params[:id]  #this will get the filename
send_file Rails.root.join(“public”, “#{id}.jpg”), type: “image/gif”, disposition: “inline” .          #send the file requested, files stored in public
end

 

This is a word around and there could (probably is) a better way, but it worked to get the project going. During refactor, we can change this and look for a better solution of need be. This was better than having to start a new rails5 app from scratch.

Advertisement

Uncaught (in promise) SyntaxError: Unexpected end of JSON input

Posted on

getting this error when using fetch to connect to my rails api

fetch(`/products/${dataid}/description`)
.then(res=>res.json())
.then(json=>console.log(json))

 

in the browser I was able to get to the page

http://127.0.0.1:3000/products/11/description

 

answer

 

rails action was rendering basic text not json, so I had to change fetch

***Rails

def description
product=Product.find(params[:id])
if product
if product.description
render plain: product.description
else
render plain: “No description”
end end end

***JS

fetch(`/products/${dataid}/description`)
.then(res=>res.text()) //<————————————-
.then(json=>console.log(json))

Could not find an executable [“phantomjs”] on your path.

Posted on

ERROR:

Got this error when running rspec.

1.2) Failure/Error:

            raise Dependency::NotFound.new(

              Could not find an executable #{@executables} on your path.)

          Cliver::Dependency::NotFound:

            Could not find an executable [“phantomjs”] on your path.

 

FIX:

gem 'phantomjs', :require => 'phantomjs/poltergeist'

I added this to my gem file, under group :development, :test do and ran bundle install

After that this error didnt come up

answer found on https://github.com/learn-co-curriculum/your-own-js-and-css-in-rails/issues/7