0
我想修改控制器中的JSON。在rails中修改嵌入對象的JSON響應/ mongoid
我有一個projects
模型embeds_many
images
使用Mongoid。
下面是型號:
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,這樣我就可以接他們的骨幹。
如果我只是在我的控制器中做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不會出現在所有..圖像好像我不能嵌套我的條件是這樣的。 如何將圖片網址加入我的JSON中?