对 Rails 控制器渲染的 JSON 进行排序

发布于 2024-12-21 21:17:49 字数 916 浏览 1 评论 0 原文

我有一个 Rails 3.1 控制器,用于呈现用户的联系人,包括关联的电子邮件对象和消息对象。如果我只渲染联系人,我可以执行以下操作:

    @contacts = @current_user.contacts.order('last_name asc', :include => [:emails, :messages])
    render json: @contacts, :include => [:emails, :messages]

如您所见,我想按姓氏而不是默认 ID 对联系人进行排序。我现在还需要渲染用户对象和其他关联对象。所以我尝试了以下操作,但当然联系人的顺序不正确:

    render :status => 200, :json => {
      :user => @current_user.as_json(
        :include => {
          :foos => {
            :except => :user_id
          },
          :contacts => {
            :except => :user_id,
            :include => [:emails,:messages]
          },
          :bars => {
            :except => :user_id
          }
        }
      )
    }

我在 as_json 文档,并且我无法通过反复试验找到正确的语法。

I have a Rails 3.1 controller that renders a user's contacts, including associated email objects and message objects. If I am only rendering the contacts, I can do the following:

    @contacts = @current_user.contacts.order('last_name asc', :include => [:emails, :messages])
    render json: @contacts, :include => [:emails, :messages]

As you can see, I want to sort the contacts by last name rather than the default id. I am now needing to render the user object with other associated objects as well. So I have tried the following, but of course the contacts are not in the appropriate order:

    render :status => 200, :json => {
      :user => @current_user.as_json(
        :include => {
          :foos => {
            :except => :user_id
          },
          :contacts => {
            :except => :user_id,
            :include => [:emails,:messages]
          },
          :bars => {
            :except => :user_id
          }
        }
      )
    }

I didn't see any help in the as_json documentation, and I haven't been able to find the right syntax by trial and error.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

绮筵 2024-12-28 21:17:49

在这种情况下,我会在 Ruby / SQL 中订购联系人,然后构建自己的 JSON 来渲染,而不是使用 as_json 及其各种 :include / : except 方法。

构建数据的哈希值,然后将其发送以进行渲染。

有各种各样的库可以使构建 JSON 变得更容易。 JBuilder 就是这样一个库。查看 JBuilder 页面底部的其他类似库的链接。

In this case I would order the contacts in Ruby / SQL and just build your own JSON to render instead of using as_json and its various :include / :except methods.

Build a hash of your data and then send it along to render.

There are all sorts of libraries that can make building JSON easier. JBuilder is one such library. Look at the bottom of the JBuilder page for links to other similar libraries.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文