lundi 6 novembre 2017

Paperclip get image URL or tag - Rails 5 JSON

I have a controller method from which I am getting all products (via Ajax):

def get_products_per_page
    limit = 40
    render json: Product.order('created_at').limit(limit).offset(params[:offset])
end

In the model Product is code for default image (from documentation):

has_attached_file :avatar, styles: { 
            medium: "300x300>", thumb: "100x100>" 
            }, 
default_url: "/images/:style/missing.png"

All products are without images (avatars). When I use Paperclip view helpers it works fine and I get the default image:

<% @products.each do |product|%>
        <li class="row">
            <div class="col-md-1">
                <%= image_tag product.avatar.url %>
            </div>
        </li>
<% end %>

But it not work when I get JSON from controller method products. In the JSON I see :

{
    avatar_file_name: null,
    avatar_content_type: null,
    avatar_file_size: null,
    avatar_updated_at: null
}

Is there way to get avatar (get the URL or URL + image tag, default avatar or none), when I query model Product like this ?

Aucun commentaire:

Enregistrer un commentaire