Question

I am working on a Padrino/Sinatra app that is using the jQuery UI Autocomplete in a certain section.

To populate the autocomplete, I have defined the following:

get '/autocompletedata' do
  content_type :json
  Foo.all.to_json(:only => :name)
end

This returns the property name from model Foo in a nice JSON array, as thus:

[{"name":"First"},{"name":"Second"},{"name":"Third"},{"name":"Fourth"}]

However, jQuery's Autocomplete requires that the name of the attribute in the returned JSON packet is labelled as label, as thus:

[{"label":"First"},{"label":"Second"},{"label":"Third"},{"label":"Fourth"}]

Is there a quick and programmatic way to change the name of the property from name to label here during the conversion process?

Failing that, can we define alias properties in DataMapper? I cannot seem to find a way to do that either?!?

Était-ce utile?

La solution

Ok, I figured out a workaround for this.

In my model Foo, I added the following method:

def label
  name
end

And then I changed the to_json options as thus:

Foo.all.to_json(:methods => :label)

and got the results I wanted. Actually, to make things work even more smoothly, I ended up narrowing down the DataMapper query some more:

Foo.all(:fields => [:name]).to_json(:methods => :label, :only => :label)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top