I have uploaded an image with active storage in rails and attached it to a model but am stuck with how i an display it with the rest of the data. Am using react and ruby at the back end both combined together. when i hit in the console Home.first.image_url it shows that the image is uploaded but when i console.log the data coming from the server the image is not included.`
here is code
here is my react front end
useEffect(() => {
let path = 'api/v1/homes'
axios.get(path)
.then(res => {
console.log(res)
setItems(res.data)
setIsLoading(false);
})
.catch(err => {
setIsLoading(false);
console.log(err)
})
}, [])
return (
<div>
}}
dataSource={items}
renderItem={(home, index) => (
<List.Item>
<Card
hoverable
title={home.title}
key={index}
cover={
<img src="${home.image_url}" />
// <img className='itemCardImage' src={home.image_url}
// onClick={() => navigate(`/details/${home.id}`)}
// />
}
am using rails 6 with active storage and am uploading image from active admin form. I am making an e-commerce website where i want admins to create products with images . below is my active admin form where image is uploaded from
form title: 'Create a new property' do |f|
f.inputs do
f.input :image, as: :file
end
f.actions
end
and here is my controller
class Api::V1::HomesController < ApplicationController
def index
@homes = Home.all.order(created_at: :desc)
render json: @homes
end
# GET /homes/1 or /homes/1.json
def show
if @home
render json: @home
else
render json: @home.errors
end
end
# POST /homes or /homes.json
def create
@home = Home.new(home_params)
if @home.save
render json: HomeSerializer.new(@home).serializable_hash[:data][:attributes]
else
render json: @home.errors
end
end
private
# Only allow a list of trusted parameters through.
def home_params
params.require(:home).permit(:title, :description, :price, :availability, :image)
end
end
here is my console from the terminal
Started GET "/${home.image_url}" for ::1 at 2023-01-31 18:04:27 0300
Processing by HomesController#index as */*
Parameters: {"unmatched"=>"${home"}
am really a new junior developer . am intention is to make a big e-commerce website that sells and rents houses and plots of land. I want admin to manage the site like creating items with images and uploads them. am using active storage in and am still in development mode.
CodePudding user response:
Mutebi you have everything nearly fine, only issue you are facing why you are unable to display images is possibly a line in your routes file for unmatched routes get "*unmatched", to: "homes#index"
so this is blocking routes from rails/activestorage.
If your change that code to something like:
match '*unmatched_route', via: :all, to: 'homes#index', constraints: lambda { |request|
request.path.exclude? 'rails/active_storage'
}
Should work perfectly fine.
CodePudding user response:
Use activerecord serializer, add attribute :image. Then with url_for rails helper you will be able to generate a url for image url.