请参考此问题:same question或another similar question
我似乎无法让我的work
脚手架包含从回形针到JSON的图像网址。我需要这个url对dom做一些ajax操作。
据我了解,您在模型中添加了一个def,然后在控制器中的format.json中添加了一行。
当我将@ work.avatar_url添加到我的控制器方法def create
时,它会引发语法错误
syntax error, unexpected ',', expecting tASSOC
我是rails和MVC的新手。所有答案都让它听起来如此简单。不幸的是,我只是猜测并检查......
我的定义创建
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
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
答案 0 :(得分:1)
尝试
format.json { render json: @work.as_json(:methods => [:avatar_url]), status: :created, location: @work }
而不是你用过的东西。