0

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
             ];

];

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

5 Comments

@iAmRubuuu i cant join due to my less reputation
you meant var events = (rest of your answered codes) shouldn't i have to inculde tags in it for ruby code differentiation?
so can i pass the events variable as it it to my javascript function? I guess your codes explains how to create array in ruby as per database values , i m trying to populate avascript array from DB values in ruby
wait does events.to_json transform the whole ruby array in javascript array events ?
yes that is generating a json array from data in db that you could consume in javascript - take a look at this for a few other options: stackoverflow.com/questions/8513912/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.