简体   繁体   English

从控制器以JSON呈现对象时,如何包含对象父级的字段?

[英]When rendering an object in JSON from the controller, how do I include a field from the object's parent?

I'm using Rails 4.2.7. 我正在使用Rails 4.2.7。 When returning an object via a show method, I want to include an object from the object's parent. 通过show方法返回对象时,我想包含来自对象父对象的对象。 I tried 我试过了

  def show
    respond_to do |format|
      @my_object = MyObject.find(params[:id])
      format.json { render :json => @my_object.to_json(:include => [:parent, :include => :address]) }
    end
  end

However this is producing the error 但是这会产生错误

NoMethodError (undefined method `include' for #<MyObject:0x007fa1b433d788>):

What's the right way to include an object from my parent? 包含我父母的对象的正确方法是什么?

Edit: here's the parent model in my Rails app 编辑:这是我的Rails应用程序中的父模型

class Parent < ActiveRecord::Base
  belongs_to :address, :autosave => true   #, dependent: :destroy

Try this one 试试这个

def show

  @my_object = MyObject.find(params[:id])
  render :json => @my_object.to_json(:include => [:parent => {:include => :address}]) 

end

You have added include within the include statement, 您已在include语句中添加了include,

@my_object.to_json(:include => [:parent, **:include** => :address])

so rails is searching include as one of the method or model. 因此,Rails正在搜索包括作为方法或模型之一。

You can use a array like this for including more than one relationship. 您可以使用这样的数组来包含多个关系。

:include => [:parent, :address]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在从Ruby对象呈现JSON之前,如何将nil更改为null? - How do I change nil to null before rendering JSON from a Ruby object? 我的控制器(Ruby / Rails)中有一个JSON对象,但我想访问Json的Object属性。 怎么做 - I have a JSON object in my Controller (Ruby/Rails) but i want to access the Json's Object attributes. How to do that Rails-将另一个对象的控制器的db字段设置为null - Rails - set a db field to null from another object's controller 如何在JSON字符串对象中包含rails项目? - How do I include rails items in a JSON string object? 如何在Rails中使用对象的控制器的create动作用对象的新实例渲染局部对象? - How can I render a partial with a new instance of my object from the create action of that object's controller in Rails? 通过jQuery从返回的JSON对象中渲染ruby对象 - Rendering a ruby object through jQuery from a returned JSON object RubyOnRails4呈现JSON时如何从has_many关系中排除属性 - RubyOnRails4 How do I exclude properties from a has_many relationship when rendering JSON 渲染部分图像并将其传递给 object 时,如何将资产中的图像显示为背景图像 - How can I show an image from assets as a background image when rendering a partial and passing it an object 我如何不包括最新记录,而是所有来自轨道对象的记录? - How do i not include latest record but all record from an object in rails? 如何从父控制器保存子记录? - How do I save my child records from the parent controller?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM