Search code examples
ruby-on-railsrubyjsonpaperclipjbuilder

Rendering Paperclip URL's using JBUILDER


I am building an API with Ruby on Rails.

I have Users that have avatars implemented using paperclip.

I am trying to access my paperclip URL's in my JSON output and it just crashed my heroku instance. This works perfectly locally.

Snippet of My User Model

class User < ActiveRecord::Base

  has_attached_file :avatar, styles: { large: "600x600#", medium: "300x300#", thumb: "100x100#" }, default_url: "https://s3.amazonaws.com/whiztutor-marketing/photos/Profile300.png"
  validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\Z/

end

Snippet of My Jbuilder for my user

json.cache! @user do
  json.id @user.id
  json.type @user.type
  json.f_name @user.f_name
  json.about @user.about
  json.email @user.email
  json.avatar_url @user.avatar.url(:medium)
  json.referral_code @user.referral_code
  json.education_level @user.education_level
  json.photo_url @user.avatar.to_json
  json.education_details @user.education_details.all
  json.all_subjects @user.subjects.all
  json.all_times @user.all_available_times.each do |time|
    json.day time.schedule.to_s
    json.time_block time.time_as_string
    json.next_occurrence time.schedule.next_occurrence(Time.now)
  end 
end

I tried wrapping this into a method as found on this question and it breaks the server the exact same way. I can even run console and access these URL's directly with the server. Something with JBUILDER and PAPERCLIP just don't mix and I can't seem to get to the bottom of it. Any help is greatly appreciated.


Solution

  • Finally diagnosed this issue after several hours of research.

    The issue is with the "json.cache! @user do" - Specifically the .cache! - I wanted to save a few server cycles and speed things up so this is how I implemented things at first.

    Regardless, when I updated my JBUILDER code to the following I am no longer getting 500 server errors.

    Snippet of My working Jbuilder for my user

    json.id @user.id
    json.type @user.type
    json.f_name @user.f_name
    json.about @user.about
    json.email @user.email
    json.small_photo @user.profile_url_small
    json.medium_photo @user.profile_url_medium
    json.referral_code @user.referral_code
    json.education_level @user.education_level
    json.education_details @user.education_details.all
    json.all_subjects @user.subjects.all
    json.all_times @user.all_available_times.each do |time|
        json.day time.schedule.to_s
        json.time_block time.time_as_string
      json.next_occurrence time.schedule.next_occurrence(Time.now)
    end