【发布时间】: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