首页 > 解决方案 > 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..

标签: ruby-on-railsruby

解决方案


根据帖子中提到的描述,您似乎没有在特定环境文件中指定资产主机。

上述答案中定义的适当方法也是在相关的 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))

希望能帮助到你!!


推荐阅读