Ruby on rails 在Rails中对回形针图像使用不同的样式,同时在json中进行渲染
我有一个模型,它有一个由曲别针管理的图像字段:Ruby on rails 在Rails中对回形针图像使用不同的样式,同时在json中进行渲染,ruby-on-rails,json,paperclip,Ruby On Rails,Json,Paperclip,我有一个模型,它有一个由曲别针管理的图像字段: class Meal < ActiveRecord::Base has_attached_file :image, :default_url => "/images/normal/missing.png", :styles => { :medium => "612x612", :small => "300x300" }, :path => ":r
class Meal < ActiveRecord::Base
has_attached_file :image, :default_url => "/images/normal/missing.png",
:styles => { :medium => "612x612", :small => "300x300" },
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename"
我正在使用render:JSON
以JSON呈现膳食
我的问题是,如何将小图像URL传递到我的fines变量(在下面的控制器中)?我希望能够像我在上面尝试的那样返回小图像URL,但在我的响应呈现时返回它(见下文)
更新:
在我的控制器中:
def view_patient
response = Response.new
this_doctor = Doctor.find_by_remember_token(Doctor.digest(auth_params["remember_token"]))
if this_doctor
this_patient = this_doctor.users.find_by_id(params[:id])
if this_patient
meals = this_patient.meals
#
# Here should be code on how to set the meals.image.url to small
glucoses = this_patient.glucoses
response.data = { :patient => this_patient, :meals => meals }
response.code = true
else
response.error = "Could not find patient"
response.code = false
end
else
response.error = "Please Login"
response.code = false
end
render :json => response.json
end
太长,读不下去了
然后可以访问JSON结构中的URL
JSON.parse(meal.to_json)['small_url']
解释
当通过将ActiveModel序列化为_json
时,首先在对象上调用方法as_json
,以将json数据结构的实际构造与呈现分离。然后通过ActiveSupport
将该数据结构(实际上是散列)编码为JSON字符串
因此,为了定制我们希望显示为JSON的对象,我们需要覆盖该对象的as_JSON
方法,这就是。根据文档,options散列的methods
键只调用作为值传递的数组中列出的方法(在我们的例子中是small\u url
),并在散列中创建一个要进行JSON编码的键,该键带有方法调用的值
要获得更详细的解释,请参阅极好的答案。Niceee,听起来这正是我需要的。我是个笨蛋,解释很贴切。和另一个问题的链接很好。我会接受当我有机会启动这个unconcey@nicohvi时,我也在用其他变量呈现我的响应,你知道如何用小URL而不是原始URL来存储我的响应吗?请参阅更新的代码。谢谢我想已经有了。当您检查
响应
JSON对象的数组时,会看到什么?我相信这个数组中的每顿饭都应该有属性small\u url
。谢谢你,爸爸,我的代码中遗漏了一些东西,是我的错
# inside meal.rb
def as_json(options=nil)
super( (options || {}).merge({
:methods => [:small_url]
}))
end
def small_url
self.image.url(:small)
end
JSON.parse(meal.to_json)['small_url']