I'm using CodeNothing's jQuery Autocomplete plugin to enable autocomplete on a text input.
The plugin needs to retreive a json object in the form:
[{ value: 'something' }, { value: 'something else' }, { value: 'another thing' }]
So, my Tag model stores its name as name, not value. To respond to this ajax request I created the following tags#index action:
def index
@tags = Tag.where("name LIKE ?", "%#{params[:value]}%")
@results = Array.new
@tags.each do |t|
@results << { :value => t.name }
end
respond_to do |format|
format.json { render :json => @results }
end
end
This is the best I could think of. It works, but it seems cludgey.
Is there a faster or better way to convert an array of Tags with a name method to an array of hashes with the form { :value => tag.name }?
Also, for bonus points, can you suggest any improvements to this controller action?
Thanks!
Note
I ended up being inspired by Deradon's answer and came up with this final implementation:
In my Tag model I added:
def to_value
{ :value => name }
end
Then in my controller I simply called:
def index
@tags = Tag.where("name LIKE ?", params[:value]+"%" )
respond_to do |format|
format.js { render :json => @tags.map(&:to_value) }
end
end
Nice, short, simple. I'm much happier with it. Thanks!