Ruby array to JSON and Rails JSON rendering

29,741

Solution 1

def autocomplete
     @question = Question.all
     respond_to do |format|
       format.json { render :json => @question }
     end
end

Solution 2

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
Share:
29,741
Mithun Sreedharan
Author by

Mithun Sreedharan

Tweets @mithunp Works @QBurst

Updated on May 02, 2020

Comments

  • Mithun Sreedharan
    Mithun Sreedharan about 4 years

    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
    
  • Jirapong
    Jirapong over 13 years
    and don't forget to give a format for your get url localhost:3000/autocomplete?format=json
  • FastSolutions
    FastSolutions about 10 years
    Thanks your answer helped me a lot!