【问题标题】:Return multiple includes on object Ruby on Rails JSON在对象 Ruby on Rails JSON 上返回多个包含
【发布时间】:2017-07-02 11:29:10
【问题描述】:

我有三个模型,并试图将它们全部作为 JSON 输出到一个对象中。

模型和关联如下:

class Customer < ApplicationRecord
  has_one :subscription
  has_one :address
end

class Address < ApplicationRecord
  belongs_to :customer
end

class Subscription < ApplicationRecord
  belongs_to :customer
end

我正在尝试使用以下命令将所有关联数据作为 JSON 返回:

class HomeController < ApplicationController
  def index
    @customers = Customer.all
    render json: @customers, :include => :address, :subscription
  end
end

但是,这会返回一个语法错误,其中 ruby​​ 在某处期待 =&gt;。对于如何输出所有这些数据的任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails json ruby activerecord


    【解决方案1】:

    如果有人在看,我刚刚用以下语法回答了这个问题。

    class HomeController < ApplicationController
      def index
        @customers = Customer.all
        render json: @customers, :include => [:address, :subscription]
      end
    end
    

    地址和订阅需要在数组中传递:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      相关资源
      最近更新 更多