ActiveRecord, << or push_with_attributes: update if exists?


#1

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 => Time.now)
  end

  # ...
end

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?


#2

Henrik wrote:

best solve this?
Here is an update_attributes method for has_and_belongs_to_many
associations:

http://encytemedia.com/blog/articles/2005/06/15/storing-additional-data-on-join-tables-with-rails#comment-490

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
method.

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.