我正在尝试修改控制器中的 JSON。
我有一个使用 Mongoid的projects
模型。embeds_many
images
以下是模型:
class Project
include Mongoid::Document
field :name, type: String
field :client, type: String
field :description, type: String
field :active, type: Boolean
attr_accessible :name, :client, :desciption, :active, :images_attributes
embeds_many :images, :cascade_callbacks => true
accepts_nested_attributes_for :images, :allow_destroy => true
end
class Image
include Mongoid::Document
include Mongoid::Paperclip
field :name, type: String
attr_accessible :file, :name
embedded_in :project, :inverse_of => :images
has_mongoid_attached_file :file,
:path => ":rails_root/public/system/:attachment/:id/:style/:filename",
:url => "/system/:attachment/:id/:style/:filename",
:styles => { :medium => "670x670>", :full => "1280x1280>", :thumb => "120x120>" }
def medium_url
self.file.url(:medium)
end
def full_url
self.file.url(:full)
end
end
现在,显然我想要 JSON 表示中的图像 URL,所以我可以在 Backbone 中获取它们。
如果我只是render :json => @projects
在我的控制器中做,我会得到以下 JSON。
[
{
_id: "the-dude",
active: false,
client: "the other dude",
created_at: "2013-04-25T11:56:06Z",
description: null,
images: [
{
_id: "51791a2620a27897dd000001",
created_at: "2013-04-25T11:57:26Z",
file_content_type: "image/jpeg",
file_file_name: "house13.jpg",
file_file_size: 182086,
file_updated_at: "2013-04-25T11:57:25+00:00",
name: "House13",
updated_at: "2013-04-25T11:57:26Z"
}, ...
所以没有网址。所以我尝试了类似的东西
render :json => @projects.as_json(only: [:_id, :name, :description, :client, images: { only: [ :_id, :name, :medium_url ], methods: [ :medium_url ]} ])
但随后图像 JSON 根本没有出现.. 似乎我不能像这样嵌套我的条件。如何将图像 URL 获取到我的 JSON 中?