If @result
is an array of ActiveRecord model instances then render :json => @result
will produce something like what you are after, but will include all the attributes of the model (render
calls to_json
on the object you pass it unless it is a string).
To only include the id and name attributes, you can use the :only
parameter of to_json
:
respond_to do |format|
format.json { render :json => @result.to_json(:only => [:id, :name] }
end
Alternatively, you can create a array of Hash objects that only contain the required attributes:
respond_to do |format|
format.json { render :json =>
@result.collect {|o| {:id => o.id, :name => o.name} } }
end
Edit: See @dt's comment below. There is an attribute in the model named text that needs to be output as name. This can be done by creating an alias for text in the model:
class Model < ActiveRecord::Base
alias_method :name, :text
and including the name using :methods
:
respond_to do |format|
format.json { render :json => @result.to_json(:only => :id, :methods => :name }
end
Alternatively, the array of hashes approach can be used to rename the attribute:
respond_to do |format|
format.json { render :json =>
@result.collect {|o| {:id => o.id, :name => o.text} } }
end