简体   繁体   中英

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

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
def autocomplete
     @question = Question.all
     respond_to do |format|
       format.json { render :json => @question }
     end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM