【发布时间】:2021-09-06 10:50:22
【问题描述】:
我使用 Rails 作为后端,React 作为前端。
我已经使用ActiveStorage 进行文件上传,并且成功上传到后端。问题是我无法将带有我的 json 的 image url 发送到我的前端以在页面上显示 image-preview。
所以我只想将所有的图片 url 发送到前端并显示出来。
products_controller.rb
# Main Preview
def index
@product = Product.paginate(:page => params[:page], per_page: 3).order(created_at: :desc)
@allProducts = Product.all
@allProductsImage = Product.all.image
@image = url_for(@allProductsImage)
@allProductsImage.map { |product|
product.as_json.merge({ image: url_for(product.image) })
}
render json: {
products: @product,
image_url: @image,
allProducts: @allProducts,
page: @product.current_page,
pages: @product.total_pages
}
end
Product.jsx
const [imageSource, setImageSource] = useState("https://image.com/1920x1080");
useEffect(() => {
AOS.init({});
fetchProducts(currentApi);
axios
.get("/api/v1/products/index", { withCredentials: true })
.then((response) => {
setImageSource(response.data.image_url);
})
.catch((error) => {
console.log("Check Login Error", error);
});
}, [imageSource]);
每次我调用 Product.image 我都会遇到 undefined method 'image' 并且在使用 Product.find(params[:id]) 之后我会遇到 cant find product by id error。
我看过一些使用序列化程序的文章,但我真的不想使用它。
如何获取每个产品的图片网址并将其呈现为 image_url 部分中的 json?
【问题讨论】:
标签: javascript ruby-on-rails json reactjs ruby