1

Is there a better way of having ajax return real-time data than creating a controller for this task and calling to it via $.ajax every so often?

For example, to fetch data from Redis, I've a controller with methods along the lines of

def get_size
 begin
  render :text => JSON.generate({:data => redis_instance.get("some_key"})
 rescue Exception => e
  render :text => JSON.generate({:data => nil})
 end
end

Then I have $.ajax call to /get_size. Is this an acceptable practice or are there far better alternatives I don't know about?

dsp_099
  • 5,801
  • 17
  • 72
  • 128

1 Answers1

1

As far as I know, yes, if you need to get data from your server via ajax you'll need to generate your own action in the controller.

The way you manipulate the data could be different, you could do it on the controller (bad bad) or in the client (better better), it depends on the aplication you are building, but using an Javascrip MVC framework it's becoming the standar way to do this. Check TODO MVC

The only thing that might be a little different is, if you need to implement a realtime feature, you could check WebSockets, and a push server like Faye ( RailsCast ) or Pusher so you don't have to pull data from rails doing a request ever X seconds.

EDIT

Also, I forgot to add that the Rails way to do ajax would be using rails.js and links with the remote: true property, so you can handle the responses with the events the script provides, like ajax:success or ajax:failure. You can check it out here.

And, in Rails 4, you can do Live Streaming for realtime.

nicosantangelo
  • 13,216
  • 3
  • 33
  • 47