user2213071
user2213071

Reputation: 101

Populate javascript array from database values in ruby

Consider following is my database table:

+-----------------------+
| Title     |   Date    |
+-----------------------+
| Meeting   | 03/28/2013|
| Lunch     | 03/09/2013|
+-----------------------+

Following is my javascript array whose values i am trying to populate as per my database values. I did it very easily with PHP but i am not able to do it with ruby kindly let me know how can I do so in ruby on rails?

Thanks,

var events = [ 
// Ruby FOR LOOP
    { Title: "% VALUE SHOULD COME HERE FROM DATABASE %", Date: new Date("% VALUE SHOULD COME HERE FROM DATABASE %") }
// END FOR LOOP
             ];

];

Upvotes: 0

Views: 516

Answers (1)

house9
house9

Reputation: 20614

If your database table is named events - The short answer is

Event.all.to_json

But you'll probably want to refine the result

events = Event.all.map do |event|
  { Title: event.title, Date: event.event_date }
end

events.to_json

NOTE: change all to use the appropriate where filters for your use case

Use I18n.localize to format your date (if needed, default should be YYYY-MM-DD, which you probably want for json data) - see http://rails-bestpractices.com/posts/42-use-i18n-localize-for-date-time-formating

Upvotes: 1

Related Questions