John Abraham
John Abraham

Reputation: 18791

Adding paperclip URL to JSON in Rails

Please reference this question: same question or another similar question

I cannot seem to get my work scaffold to include the image URL from paperclip to JSON. I need this url to do some ajax manipulation to the dom.

To my understanding you add a def in a model and then you add a extra line to the format.json in the controller.

when I add the @work.avatar_url to my controller method def create it throws up a syntax error

syntax error, unexpected ',', expecting tASSOC

I'm really new to rails and MVC. All the answers make it sound so easy. Unfortunately, I'm just guessing and checking...

Controller Link: works_controller.rb

My Def Create

def create
    @work = Work.new(params[:work])


    respond_to do |format|
      if @work.save
        format.html { redirect_to @work, notice: 'Work was successfully created.' }
        format.json { render json: @work, status: :created, location: @work }
      else
        format.html { render action: "new" }
        format.json { render json: @work.errors, status: :unprocessable_entity }
      end
    end
  end

Git Link Model: work.rb

class Work < ActiveRecord::Base
  validates :name, :presence => true

  has_many  :categoryworks
  has_many :categories, :through => :categoryworks
  accepts_nested_attributes_for :categories
  attr_accessible :name, :subtitle, :category_ids, :svg, :post_a, :post_b, :post_c, :post_d, :avatar
  has_attached_file :avatar, :styles => { :medium => "1280x700>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"

   def avatar_url
     avatar.url(:medium)
   end

end

Upvotes: 0

Views: 1146

Answers (1)

logesh
logesh

Reputation: 2662

Try

format.json { render json: @work.as_json(:methods => [:avatar_url]), status: :created, location: @work }

instead of what you have used.

Upvotes: 1

Related Questions