Created
March 30, 2010 08:53
-
-
Save CodeOfficer/348925 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# In Rails 3, I wanted to include some additional json values in my data for | |
# the jquery ui autocomplete plugin. Overriding to_json() at the model level | |
# seemed to work on a specific model instance, but not for a collection of | |
# model instances. (pretty sure that worked in prior Rails versions) | |
# Here's the working code: | |
class PostsController < ApplicationController | |
def index | |
@posts = Post.all | |
respond_to do |format| | |
format.html # index.html.erb | |
format.json { render :json => @posts.to_json } | |
end | |
end | |
def show | |
@post = Post.find(params[:id]) | |
respond_to do |format| | |
format.html # show.html.erb | |
format.json { render :json => @post.to_json } | |
end | |
end | |
end | |
class Post < ActiveRecord::Base | |
JSON_ATTRS = ['title', 'body'] | |
def as_json(options = nil) | |
attributes.slice(*JSON_ATTRS).merge(:label => title, :value => id) | |
end | |
end | |
# solution found here: | |
# *** Synchronizing Core Data With Rails (slide #28) *** | |
# http://www.slideshare.net/metaskills/synchronizing-core-data-with-rails |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment