I think this might do what you want:
def index
render :json => Event.all.to_json :methods => :event_summary
end
[EDIT]
IIRC respond_with doesn't work with to_json, so you have to use render
Question
Part of an application I'm building is an API. Recent changes mean that I need to put two different versions of the data into my json feed. I think the best way to do this is to make the necessary changes in the database then create a virtual attribute to concatenate the data.
In my model I have the event_summary virtual attribute which there's no issue with outputting in views using <%= @event.event_summary =>
:
def event_summary
"#{title} (#{start_datetime.strftime('%A %d %b, %l:%M%P')})"
end
In my API controller I have a select query which gets the attributes I need for the API response (simplified version here):
respond_to :json
def index
respond_with Event.select('title, event_summary')
end
The problem is that it always returns an undefined column error:
PG::UndefinedColumn: ERROR: column "event_summary" does not exist LINE 1: SELECT title, event_summary FROM "events"
I also tried the following but got the same result:
respond_with Event.select('title', :event_summary)
I'm using Postgres if that makes any difference.
Is there a way to do this?
Thanks!
Solution 2
I think this might do what you want:
def index
render :json => Event.all.to_json :methods => :event_summary
end
[EDIT]
IIRC respond_with doesn't work with to_json, so you have to use render
OTHER TIPS
You can't use virtual attributes in the select method because it will be turned into a SQL statement and that field doesn't exist in your table. You could however, do the concatenation and date formatting in SQL:
Event.select('title, (title || ' ' || to_char(start_datetime, 'HH12:MI:SS')) as event_summary')
That will in effect create a "virtual attribute" but in sql land and it will return events with that attribute present and formatted by the to_char
postgres method. The date formatting isn't exactly what you had, so you'll need to tweak it to your needs (by changing the format string 'HH12:MI:SS'
) as detailed in the docs here: http://www.postgresql.org/docs/8.2/static/functions-formatting.html
Hope that helps.