Store a single variable / row in database

What would be the best way in rails to store a single variable and have
it persist. Like a have a variable that says “total_visits” that counts
the total number of page loads.

The only solution I can think of is having a table with a single row.

What would be the best way in rails to store a single variable and have
it persist. Like a have a variable that says “total_visits” that counts
the total number of page loads.

The only solution I can think of is having a table with a single row.

One answer would be yes, pretty much if you really want to store a
single data point that’s accessible to a number of instances of Rails,
then either a file or a database is what you’ll need to use (assuming
you don’t trust anything RAM based).

However, your specific scenario could quickly become an extreme
bottleneck. It would be better served by logging (preferably
asynchronously), and then read & tally the log to create your total. Do
it periodically, so you’re not starting from the first log every every
time.

There’s probably other ways, but using a single var for something like
page loads is looking for trouble as your app scales. If you know the
page requests will be low enough to not be a bottleneck then using the
DB with row or table locking (effectively the same for this case) might
be OK.

Another option if you can tolerate the potential for a little inaccuracy
is to go ahead and use RAM (with a mutex) to keep the count, and
periodically write that value to disk to minimize the disk access. If
you have load balanced app servers you’ll need a central RAM cache like
memcache.

That’s what comes to my mind – others may have better ideas.

– gw

IMHO The biggest problem with rails is the fact that it makes working
easy and fun as long as your work can follow the MVC system. If you
try to do it your way it won’t be the rails way (at least as far as I
know).

If you want to track any more information other then number of pages
views, create a page_view model and give it some logic to do the rest
of your magic. If you want to track views of a specific model, add a
page_views field to that model. If you just want to track the number
of page views on your entire website… use an analytics program :slight_smile:

Brian

Well, specifically what it would be for is an app which parses /
collects stats on twitter. I want to have a persistant of the ID
(twitter side) of the most recent parsed tweet, so I know where to start
at the next startup, or in case it gets interrupted.

I don’t what to log every tweet I parse to the database (there are tens
of thousands), nor do I need to.

So a single-row table would be the best way to do this?

change your question to

how can count the total number of page loads for … ?

For what?