(RoR)json和嵌套对象:获取对象对象中的属性

时间:2016-03-02 17:48:06

标签: ruby-on-rails json ruby-on-rails-4

我的目标是这样的输出(对于每个附件):

  

URL:   " /uploads/attachment/picture/15/5ee306c9-e263-466b-b56d-1c7c9d2ae17b.jpg"

我现在所拥有的:

json object in object

attachments_controller.rb

class AttachmentsController < ApplicationController
  before_action :logged_in_user

  def index
    @attachments = current_user.attachments.all
    respond_to do |format|
      format.json do
        render :json => @attachments.each{ |o| o.picture.url }
      end
    end
  end

...

1 个答案:

答案 0 :(得分:1)

尝试

respond_to do |format|
  format.json do
    render :json => @attachments.map { |o| { url: o.picture.url } }
  end
end