ruby-on-rails - How can I get complete absolute URL for paperclip attachment?
问题描述
I'm working on JSON data, I want to display complete image url with localhost name but I'm getting half item_image_url..
"item_image_url": "/system/images/item_images/000/000/001/original/images_%284%29.jpeg?1545807832"
{
"id": 1,
"title": "Pasta",
"filename": "Burger.",
"item_image_file_name": "images_(4).jpeg",
"item_image_content_type": "image/jpeg",
"item_image_file_size": 12944,
"item_image_updated_at": "2018-12-26T07:03:52.284Z",
"updated_at": "2018-12-26T07:03:52.355Z",
"created_at": "2018-12-26T07:03:52.355Z",
"item_image_url": "/system/images/item_images/000/000/001/original/images_%284%29.jpeg?1545807832"
}
how can i get this complete ulr like this http://localhost:3000/system/images/item_images/000/000/001/original/images_%284%29.jpeg?1545807832
in controller
class V1::ImagesController < ApplicationController
skip_before_action :verify_authenticity_token
def index
@images = Image.all
render :json => @images.to_json(:methods => [:item_image_url])
end
def show
image = Image.find(params[:id])
render json: {status: 'success', data:image},status: :ok
end
def create
image = Image.new(image_params)
if image.save
render json: {status: 'success', data:image},status: :ok
else
render json: {status: 'error', message:'image not saved', data:image.errors},status: :unprocessable_entity
end
end
def destroy
image = Image.find(params[:id])
image.destory
render json: {status: 'success', data:image},status: :ok
end
private def image_params
params.permit(:item_image_url,:title,:filename)
end
end
in model
class Image < ApplicationRecord
has_attached_file :item_image, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
validates_attachment_content_type :item_image, content_type: /\Aimage\/.*\z/
def item_image_url
self.item_image.url(:original)
end
end
Pleas need help..
解决方案
根据帖子中提到的描述,您似乎没有在特定环境文件中指定资产主机。
上述答案中定义的适当方法也是在相关的 config/environments/{environment} 文件中定义资产主机:其中上述行中提到的环境表示 development.rb、production.rb 和 test.rb(others以及如果您定义了自定义环境)
onfig.action_controller.asset_host = "http://localhost:3000"
如果您想在视图中访问它,请使用下面提到的代码:
asset_url(model.attachment.url(:style))
如果您想访问它的rails控制台,请使用下面提到的代码
helper.asset_url(model.attachment.url(:style))
如果您想在模型中使用它,请使用下面提到的代码:
ApplicationController.helpers.asset_url(model.attachment.url(:style))
希望能帮助到你!!
推荐阅读
- reactjs - 如何将 npm 库中的样式连接到使用 css-modules 的项目?
- haskell - (Num p) 没有因使用“+”而产生的实例
- c# - 将程序集加载到 AppDomain
- java - 我有时在解密字符串时遇到 BadPadding 异常
- javascript - 拆分字符串,然后将其添加到另一个变量并包含未定义
- node.js - AWS compareFaces() Rekognition Javascript SDK 错误:无法从 S3 获取对象元数据。检查对象键、区域和/或访问权限
- unreal-engine4 - 虚幻引擎无法启动 - 问题 0xc0000005
- html - 被上面的文本量下推和截断的文本
- android - 在 Oreo TV 应用程序中执行应用程序链接以使用谷歌助手进行应用程序内搜索
- spring-boot - 如何使用 spring-messaging-5.1.* 连接 stomp+ssl 代理?