LearningRoR
LearningRoR

Reputation: 27212

How to watch a model for changes?

Lets say you have 2 models...

Store :has_many products 
Product :belongs_to store

..and the Product model has the attribute :price.

I want to have a view that shows users of updated prices of products if they go down in cost. I'm not sure where to start though. What about if I wanted to give the users the choice of which products to watch? How would you set this up?

Upvotes: 3

Views: 420

Answers (3)

Wolfram Arnold
Wolfram Arnold

Reputation: 7273

You could start with ActiveRecord Observers on your price model to trigger a notification every time a price changes.

You could then fan out these notifications across a list of subscribers. There are a number of solutions for pub/sub frameworks. One is Rails's native built-in Notification API, explained in detail in José Valim's book Crafting Rails Applications. Another one is the Faye gem, take a look at their site.

Other options are EventMachine, Node.js, or Websockets.

Upvotes: 3

Michael Durrant
Michael Durrant

Reputation: 96484

I would use ajax with polling.

On the server side I would have a background job (choose from backgroundrb, rescue, cron, etc). Every polling interval I would see if things have changed and if so show the content.

I would track what changes usng timestamps and comparing to Now().

Upvotes: 1

ksol
ksol

Reputation: 12235

What I'd do is add a field "trend" or something like that, that I would update each time the price changes (with a callback or an observer), and set it to "increase/decrease", or something that has that meaning. Then, I'd look for all the products where the trend is decrease and that were updated (according to updated_at) recently, recently being a value you define, it can be "in the last two weeks", "since user last login", etc etc.

Upvotes: 2

Related Questions