在Rails中将回形针URL添加到JSON

时间:2013-07-18 02:14:56

标签: ruby-on-rails json paperclip rails-activerecord

请参考此问题:same questionanother similar question

我似乎无法让我的work脚手架包含从回形针到JSON的图像网址。我需要这个url对dom做一些ajax操作。

据我了解,您在模型中添加了一个def,然后在控制器中的format.json中添加了一行。

当我将@ work.avatar_url添加到我的控制器方法def create时,它会引发语法错误

syntax error, unexpected ',', expecting tASSOC

我是rails和MVC的新手。所有答案都让它听起来如此简单。不幸的是,我只是猜测并检查......

Controller Link: works_controller.rb

我的定义创建

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模型: 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

1 个答案:

答案 0 :(得分:1)

尝试

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

而不是你用过的东西。