Michael Pavling wrote: > On 19 August 2010 21:18, Philip Hallstrom <[email protected]> wrote: >> Don't use increment. �It won't do what you want since it's only incrementing >> the value of the object and then saving it. �Not updating the value in the >> database. > > What is "saving" if not updating in the database? > >> You want to use increment_counter which calls update_counters which does >> this in the database: > > What is the result of your "u" "u1" console experiment when you use > increment_counter rather than increment? > As far as I can see it will be the same - you've got two copies of an > object loaded, and you update one, without reloading the other; of > course that can lead to race conditions and stale data.
Besides this. According the the Rails docs, increment_counter is typically used for caching aggregate values. That's not the case here since the field to be incremented is not related to an associated model. The increment_counter would make sense for things like caching the count of comments on a post model to prevent the SQL query that would be required to count the associated comments. And, of course, that race condition exists in your console experiment, but that's not an issue in the controller method I presented earlier. The @poem instance would be garbage collected at the end of the request-response cycle. Other methods would have to reload from the database anyway. So I don't see a problem using the increment! method here. ------------------------------ def show @poem = Poem.find(params[:id]) @poem.increment!(:view_count) ... ... end ------------------------------ -- Posted via http://www.ruby-forum.com/. -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

