2013-05-05 59 views
0

我想修改控制器中的JSON。在rails中修改嵌入對象的JSON響應/ mongoid

我有一個projects模型embeds_manyimages使用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中?

回答

1

好吧,我通過使用優秀的rabl寶石解決了這個問題。

# views/projects/index.json.rabl 
collection @projects 
attributes :_id, :name, :description, :client 

child :images do 
    attributes :name 
    node :medium_url do |img| 
    img.file.url(:medium) 
    end 
    node :full_url do |img| 
    img.file.url(:full) 
    end 
end 
在我的控制器

只有

def index 
    @projects = Project.all 
end 

,現在我的JSON看起來應該:

{ 
project: { 
_id: "moe-ho", 
name: "Moe Ho", 
description: null, 
client: "tripple A", 
images: [ 
    { 
    name: "Img 2179", 
    medium_url: "/system/files/51854f546c22b89059000006/medium/IMG_2179.JPG?1367691092", 
    full_url: "/system/files/51854f546c22b89059000006/full/IMG_2179.JPG?1367691092" 
    }, 
    { 
    name: "Img 2192", 
    medium_url: "/system/files/51854f556c22b8b13e000007/medium/IMG_2192.JPG?1367691092", 
    full_url: "/system/files/51854f556c22b8b13e000007/full/IMG_2192.JPG?1367691092" 
    }, ...