【发布时间】:2021-12-20 22:27:55
【问题描述】:
我有一个带有 has_one: itemPphoto 的模型项目的 Rails API。我正在使用activeStorage 将图像上传到 Cloudinary。我也在使用 Administrate gem,这是我使用表单将图像上传到 Cloudinary 的地方,这部分正在工作。我坚持的部分是在 React 中,我想显示我为每个项目上传的每张图片,但到目前为止我还没有运气。我希望我在下面正确显示代码,这是我第一次。如果您仔细查看我的 JS,我可以显示图像,但我必须调用特定的 cld.image(imageName),但我想找到一种方法来映射我的项目并显示每个项目的图像。
- 型号:item.rb
class Item < ApplicationRecord
has_one_attached :itemPhoto
validates_presence_of :itemName,
:itemPrice
end
- 控制器:items_controller.rb
class Api::V1::ItemsController < ApplicationController
def index
@items = Item.all
render json: @items.to_json(include: {
itemPhoto: {
include: :blob
}
})
end
private
def item_params
params.require(:item).permit(:itemPhoto, :itemName, :itemPrice)
end
end
在我的前端 3. itemList.js
import { Card } from 'react-bootstrap';
import PropTypes from 'prop-types';
import { Cloudinary } from '@cloudinary/url-gen';
const ItemList = ({ items }) => {
const cld = new Cloudinary({
cloud: {
cloudName: 'cloudName',
},
url: {
secure: true, // force https, set to false to force http
},
});
const myImage = cld.image('p6a1m4z8avkvxt0gwhdssnnk6mbk');
const myURL = myImage.toURL();
return (
<div className="container-fluid flex-column justify-content-center">
{
items.map((items) => (
<Card
key={items.id}
>
<table className=" m-3 col-10">
<tbody className=" col-12">
<tr className=" m-3 ">
<div className="m-3 col-12 flex-container justify-content-center">
<div className="col-12 d-flex justify-content-center">
<div className="col-12 d-flex justify-content-center">
<p className=" col-8 d-flex justify-content-center serviceCategoryTitle p-2">{ items.id }</p>
<p className=" col-8 d-flex justify-content-center serviceCategoryTitle p-2">{ items.itemName }</p>
<p className=" col-8 d-flex justify-content-center serviceCategoryTitle p-2">{ items.itemDescription }</p>
<p className=" col-8 d-flex justify-content-center serviceCategoryTitle p-2">{ items.itemPrice }</p>
<img src={myURL} alt=" " />
<img src={items.itemPhoto} alt=" " />
</div>
</div>
</div>
</tr>
</tbody>
<hr className=" col-12 " />
</table>
</Card>
))
}
</div>
);
};
ItemList.propTypes = {
items: PropTypes.arrayOf(PropTypes.array).isRequired,
};
export default ItemList;
**strong text**
【问题讨论】:
标签: reactjs ruby-on-rails cloudinary