Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby array to JSON and Rails JSON rendering

I have a Ruby array, how can i render this as a JSON view in Rails 3.0?

My Controller method is

def autocomplete
     @question = Question.all
end
like image 424
Mithun Sreedharan Avatar asked Nov 23 '10 06:11

Mithun Sreedharan


2 Answers

If the autocomplete action is only rendering JSON, you could simplify re5et's solution to:

def autocomplete
  questions = Question.all
  render :json => questions
end

(note that I pluralized 'question' to reflect that it is an array and removed the @ symbol - a local variable suffices since you're probably only using it to render inline JSON)

As kind of an addendum, because I suspect people might land on this page looking for a solution to the jquery ui autocomplete plugin, rendering the array question to JSON won't work. The plugin requires a specific format as described here:

The local data can be a simple Array of Strings, or it contains Objects for each item in the array, with either a label or value property or both. The label property is displayed in the suggestion menu. The value will be inserted into the input element after the user selected something from the menu. If just one property is specified, it will be used for both, eg. if you provide only value-properties, the value will also be used as the label.

When a String is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The request parameter "term" gets added to that URL. The data itself can be in the same format as the local data described above.

In other words, your json should look something like this (in its simplest form):

[{'value': "Option1"},{'value': "Option2"},{'value': "etc"}]

You could accomplish this in ruby like so:

def autocomplete
  questions = Question.all # <- not too useful
  questions.map! {|question| {:value => question.content}}
  render :json => questions
end

I haven't tested this since I don't have my dev box handy. I will confirm in a few hours when I do.

UPDATE: yup, that works!

UPDATE 2:

The new rails way to do this (added in rails 3.1) would be:

class MyController < ApplicationController
  respond_to :json
  # ...
  def autocomplete
    questions = Question.all # <- not too useful
    questions.map! {|question| {value: question.content}}
    respond_with(questions)
  end
end
like image 172
Pierre Avatar answered Oct 19 '22 02:10

Pierre


def autocomplete
     @question = Question.all
     respond_to do |format|
       format.json { render :json => @question }
     end
end
like image 20
re5et Avatar answered Oct 19 '22 02:10

re5et