Json output | changing field names

so here’s what I have in my responds_to block


      format.json { render :json => @users.to_json(:only => [:id, :first_name, :last_name]) }

But what I’m needing to come back is the :id field to be labeled “value” and then combine the :first_name and :last_name into a “label”.

The autocomplete javascript I’m using is looking for “label” and “value” fields to populate the dropdown. Been searching and this seems to be a pain point on rails. Isn’t there a way to specify a index.json.erb file and have it use that to build a response?

Any help/advice is appreciated.

ugh… my mistake. It’s working as expected.

Put the methods in the wrong stinking model!

Thanks for the help.

Huh, that’s really weird. Have a look at the :methods example in the api docs here: http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html#M001365

The permalink example they give is much the same as what you’re trying to do, unless the docs are out of date?

dang… got all excited for a moment. Virtual attribute… DUH! but alas… it’s not working. If I use :methods the entire record comes back (but no label or value attributes) and if I use :only, then nothing comes back. :frowning:

Ok, so I’m not sure if this is the best way to do it, but I’m pretty sure it will work. Create methods in your model class for each “attribute” you need. For example:

def label
  [first_name, last_name].join(' ')
end

Then, when you call to_json, use the methods option, like this:

format.json { render :json => @users.to_json( :methods => :label ) }

As an added bonus, you now have access to that concatenated name anywhere else you need it, which might simplify your views a little.

Let me know if that works!