Forum: Ruby on Rails ActiveRecord, << or push_with_attributes: update if exists?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Henrik -. (Guest)
on 2006-01-02 20:49
In the Agile Rails book, on page 232 (PDF, 4th edition) there is an
example of (within ActiveRecord) marking an article as read by a user at
the present time. Short example code (from the book) here:

	class User < ActiveRecord::Base
	  has_and_belongs_to_many :articles

	  def read_article(article)
	    articles.push_with_attributes(article, :read_at =>

	  # ...

However, it seems this piece of code would only work the first time you
read a specific article. It appears to always create a new join table
post, and not to just update if there is an existing post. How would one
best solve this?
Mark Reginald J. (Guest)
on 2006-01-03 02:31
(Received via mailing list)
Henrik wrote:

> best solve this?
Here is an update_attributes method for has_and_belongs_to_many

However: (1) I would have thought this goes in a file in lib rather than
              in application_helper.rb,
          (2) The "end" on the first line shouldn't be there, and
          (3) "> 0" could be added to the end of the DB call so that a
               boolean is returned like the usual update_attributes

Are there any other solutions out there?  Should something like this be
added to the ActiveRecord distribution?

We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.