ruby-on-rails - rails : include related object in

我有一个属于用户的笔记类(即一个用户可以创建许多笔记)。

来 self 的笔记 Controller 的剪辑

class NotesController < ApplicationController
  before_filter :authenticate_user!
  respond_to :html, :xml, :json

  # GET /notes
  # GET /notes.xml
  def index
    @notes = Note.includes(:user).order("created_at DESC")
    respond_with @notes
  end

当我请求 json 结果中的索引(例如/notes.json)时,它会返回注释,但只返回用户对象的 user_id。我希望它还包含 user.username(并且很好奇如何嵌入整个用户对象)。

额外问题:我找不到让列显示为 author_id 并将其与用户相关联的方法。如果这很容易做到,你是怎么做到的?

最佳答案

我不确定新的 respond_to/respond_with 样式是否足够灵活以执行此操作。很可能是这样,但据我了解,这只是为了简化最简单的情况。

您可以使用带有 block 的旧式 respond_to 来实现您想要做的事情,但是,通过将参数传递给 to_json。试试这样的:

class NotesController < ApplicationController
  def index
    @notes = Note.order("created_at desc")
    respond_to do |format|
      format.json do
        render :json => @notes.to_json(:include => { :user => { :only => :username } })
      end
    end
  end
end

关于ruby-on-rails - rails : include related object in JSON output,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4582121/

相关文章:

c++ - 使用 boost 属性树读取 int 数组

json - 我可以使用哪些程序来可视化 JSON 文件?

java - 使用 JAX-RS 将 JSON 查询参数转换为对象

json - 使用新参数 ExtJs Ext.data.JsonStore 重新加载 json 存储

json - 如何在自定义 JsonConverter 中使用默认序列化

json - 如何将有向无环图 (DAG) 存储为 JSON?

json - 谷歌金融 json 股票报价停止工作

java - 如何使用 gson 调用默认反序列化

SQL to JSON - SQL 2016 中的对象数组到值数组

json - 如何找出实际安装了哪个版本的 bower 包?