Convert attribute of two models to json response

I am on a ruby ​​on rails and I have two models, the goal is to search the site on two models, I use twitter typeahead, but the problem I have is json, which should be a single object.

I'm not sure the best way to convert my two objects into one. Here is the code

@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 

I'm not sure what the best way is, or I can't find the best documentation to combine these two models into one. I don't know if to_json, as_json or concat would be better.

The idea is to get the result of the next json from

 {"art":["John","Serge","Dean","feng","Heather"],"user":["Ontario high school teachers drop next week walkout plan","Air Canada to appeal Quebec court ruling on Aveos"]} 

To the next

 {"result":["John","Serge","Dean","feng","Heather", "Ontario high school teachers drop next week walkout plan","Air Canada to appeal Quebec court ruling on Aveos"]} 
+4
source share
2 answers

So, if you want to get an array of both users and articles:

 respond_to do |format| format.json { render :json => {:art => @articles, :user => @users }} end end 

Based on your edit:

 format.json { render :json => { result => @articles.map(&:title) | @users.map(&:first_name) }} 

Based on the last comment, just catch the problem with zero:

 format.json { render :json => { result => (@articles.map(&:title) || []) | (@users.map(&:first_name) || []) }} 
+2
source

May I suggest using a JSON presentation template. There are many options for you, but the two most popular are RABL and JBuilder. I can highly recommend RABL stone.

There is a reason for their popularity, they are rendering json a breeze

You can find the RABL gem here https://github.com/nesquena/rabl

Here you can find the JBuilder gem https://github.com/rails/jbuilder

Both of them have excellent rails showing how to use them.

RABL http://railscasts.com/episodes/322-rabl

JBuilder http://railscasts.com/episodes/320-jbuilder

I prefer RABL solely from my personal preferences, you should look at both options to see what works best for you.

Adding a gem is usually not something that I would recommend, but I think you will find that any of these solutions will suit your needs.

+2
source

All Articles