ruby-on-rails – 在json响应中转换两个模型属性
发布时间:2020-12-17 02:33:56 所属栏目:百科 来源:网络整理
导读:我在轨道上的ruby,我有两个模型,目标是在两个模型上搜索网站,我使用twitter typeahead,但我有的问题是json必须是一个对象. 我不确定将两个对象转换为一个的最佳方法是什么.这里的代码 @users= Search.user(params[:query])@articles= Search.article(params[
|
我在轨道上的ruby,我有两个模型,目标是在两个模型上搜索网站,我使用twitter typeahead,但我有的问题是json必须是一个对象.
我不确定将两个对象转换为一个的最佳方法是什么.这里的代码 @users= Search.user(params[:query])
@articles= Search.article(params[:query])
respond_to do |format|
format.html # index.html.erb
format.json {
render :json => {
:art=> @articles.map(&:title),:user=> @users.map(&:first_name)
}}
end
end
我不知道最好的方法是什么,或者我似乎无法找到将这两个模型合并为一个的最佳文档.我不知道to_json,as_json或concat是否是最好的. 这个想法是得到以下json的结果 {"art":["John","Serge","Dean","feng","Heather"],"user":["Ontario high school teachers drop next week's walkout plan","Air Canada to appeal Quebec court ruling on Aveos"]}
以下 {"result":["John","Heather","Ontario high school teachers drop next week's walkout plan","Air Canada to appeal Quebec court ruling on Aveos"]}
解决方法
因此,如果您想获得用户和文章的数组:
respond_to do |format|
format.json { render :json => {:art => @articles,:user => @users }}
end
end
根据您的编辑: format.json {
render :json => {
result => @articles.map(&:title) | @users.map(&:first_name)
}}
根据最后的评论,只是陷入零问题: format.json {
render :json => {
result => (@articles.map(&:title) || []) | (@users.map(&:first_name) || [])
}}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
