【问题标题】:How to get full belongs_to object in json render?如何在 json 渲染中获取完整的 belongs_to 对象?
【发布时间】:2018-07-20 18:19:45
【问题描述】:

基本上,我有一个属于 :companies 的对象,并且具有 :company_id 属性。当我渲染 json:@coupons 时,JSON 是否可以包含其所有者的属性而不是 company_id?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您也许可以执行render :json => @coupons.to_json(:include => :company) 之类的操作,至少它似乎适用于我在 rails 2.3.8 中的初始测试。

    答案已编辑为使用 :include => :company 而不是 :include => :companies

    【讨论】:

    • 优惠券真的属于:companies(复数)吗?如果没有,请尝试上述方法,但 :include => :company
    【解决方案2】:

    如果您需要使 json 尽可能紧凑,最好使用自定义模型方法仅返回您需要的数据。我最终向父模型添加了一个自定义 as_json 方法,并使用 methods 选项返回相关对象数据的子集。使用 include 将包含相关模型的完整 json 序列化。

    def as_json(options={})
      super(
        :only => [:id, :name],
        :methods => [
          :organization_type_name,
        ]
      )
    end
    
    def organization_type_name
      self.organization_type.name
    end
    

    【讨论】:

      【解决方案3】:

      首先你的约定是错误的。

      应该是

      //在coupon.rb中

      belongs_to :company
      

      在渲染对象时这样做

      render json: @coupon.as_json(include: :company)
      

      【讨论】:

        猜你喜欢
        • 2012-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-06
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        相关资源
        最近更新 更多