【问题标题】:Rendering Two JSON Items In Rails在 Rails 中渲染两个 JSON 项
【发布时间】:2019-04-21 18:01:40
【问题描述】:

这似乎是一个重复的问题,但其他帖子上的答案似乎不适用于我的问题。

我需要在我的控制器的 index 方法中呈现两个 JSON 项:

 def index
    @user = User.all
    @libraries = Library.all.order(:created_at)

    user_cards = current_user.libraries

    render :json => @libraries, :include => :user
    render :json => user_cards
  end

我试图这样做(失败并出现 500 错误):

render :json => @libraries, user_cards, :include => :user

我也尝试过这样做(同样失败并出现 500 错误):render :json => @libraries :include => [:user, :user_cards]

更新

这是正确渲染 json 的最新尝试:

def index
    @user = User.all
    @libraries = Library.all.order(:created_at)

    user_cards = current_user.libraries

    render json: {
      user_cards: user_cards,
      libraries: @libraries.as_json(include: [:user])
    }
  end

这个问题是我现在在整个应用程序中遇到libraries 的错误。如果我只是像最初那样渲染 json (render :json => @libraries, :include => :user),我不会收到此错误。所以,我假设我拥有它的方式仍然不正确。 libraries 的确切错误是在我使用过滤器的 React 组件之一中调用的:

错误:Uncaught TypeError: this.props.librarys.filter is not a function

错误位置:

let filteredCards = this.props.librarys.filter(
        (library) => {
          return library.title.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1 || library.desc.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1
        }
      )

【问题讨论】:

    标签: ruby-on-rails json reactjs


    【解决方案1】:

    控制器只能返回一个响应,你可以将这两个返回合二为一:

    respond_to do |format|
      format.json  { render json: { user_cards: user_cards,
                                    libraries: @libraries } }
    end
    

    【讨论】:

    • 非常感谢您的帮助!我如何仍然使用这种格式的:include => :user
    • 试试这个:libraries: @libraries.to_json(include: [:user] )
    • 再次感谢您的帮助。它实际上是在respond_to 上给我noMethodError。包含和其他一切似乎都很好,只是奇怪它是如何给我这个错误的。
    • 你在api模式下使用rails吗?那里没有 respond_to 方法。尝试不使用respond_to do |format|,只需render json: ...
    • 感谢您一直以来的帮助!删除 respond_to 确实有帮助,因为我在 api 模式下使用 rails。即使我不再收到 500 错误,我也不认为它目前正在工作。我会更新我原来的帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    • 2012-03-03
    相关资源
    最近更新 更多