ActiveRecord:


#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

On Jan 2, 2006, at 11:48 AM, Henrik wrote:

end

It looks like the intent is to create some sort of ‘log’ of each
visit. However, if this is not the intent, then you could
(potentially) use “articles.clear” before calling
articles.push_with_attributes. Unfortunately, destroying all
associated articles may not be the desired result, either.

If you just want to delete articles of a certain ID you can use
articles.delete(article), and then call push_with_attributes.

Duane J.
(canadaduane)
http://blog.inquirylabs.com/


#3

That last (articles.delete) would do the trick. Thanks! I was hoping for
a “cleaner” way to do it, ideally something like (pseudo-Ruby)
articles.push_or_update_with_attributes, but I suppose this is as good
as it gets.

Duane J. wrote:

On Jan 2, 2006, at 11:48 AM, Henrik wrote:

end

It looks like the intent is to create some sort of ‘log’ of each
visit. However, if this is not the intent, then you could
(potentially) use “articles.clear” before calling
articles.push_with_attributes. Unfortunately, destroying all
associated articles may not be the desired result, either.

If you just want to delete articles of a certain ID you can use
articles.delete(article), and then call push_with_attributes.

Duane J.
(canadaduane)
http://blog.inquirylabs.com/