我有一个模型,它有一个由回形针管理的图像字段:
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"
我可以访问不同的尺寸,如下所示:
meals.each do |n|
n.image.url(:small) # gives url for small images
puts n.image.url # returns url for original images, I want this to return small for this function
end
我使用render :json
在JSON中呈现餐食。
我的问题是,如何将小图像URL传递到我的膳食变量中(在下面的控制器中)?我希望能够像上面尝试的那样返回小图像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
TLDR
# inside meal.rb
def as_json(options=nil)
super( (options || {}).merge({
:methods => [:small_url]
}))
end
def small_url
self.image.url(:small)
end
然后,您可以访问JSON结构中的URL
JSON.parse(meal.to_json)['small_url']
解释
当ActiveModel通过to_json
序列化时,首先在对象上调用方法as_json
,以将JSON数据结构的实际构造与呈现分离。然后通过ActiveSupport
将该数据结构(实际上是一个散列)编码为JSON字符串。
因此,为了自定义我们希望显示为JSON的对象,我们需要覆盖该对象的as_json
方法——这已经有很好的文档记录了。根据文档,选项哈希的methods
键只需调用数组中列出的作为值传递的方法(在我们的情况下仅为small_url
),并在哈希中创建一个要进行JSON编码的键,其中包含方法调用的值。
如需更详细的解释,请参阅此优秀答案。