0

我正在尝试修改控制器中的 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 中?

4

1 回答 1

1

好的,我通过使用优秀的rablgem 解决了这个问题。

# 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"
  }, ...
于 2013-05-05T15:12:49.667 回答