Forum: Ruby on Rails Updating Attributes in a HABTM Join Table

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kevin S. (Guest)
on 2006-01-05 01:57
(Received via mailing list)
Is there a way to update attributes in a HABTM join table?  Right now
I am deleting the join and then recreating it with new attributes.

I have a table "categories" and another table "items".  They are both
HABTM with the join table "categories_items" between them. If an item
is joined to a category once, no problem, we create the join.  But if
an item is joined to a category more than once, I want to record the
subsequent hit in a field called "cat_count" which exists in the join
table.

def add_category( category_id_as_str )

	category = Category.find(category_id_as_str.to_i)

	if self.categories.include?(category)
		old_count = self.categories.find(category.id).cat_count.to_i
		self.categories.delete(category)
	else
		old_count = 0
	end
	self.categories.push_with_attributes(category, :cat_count =>
old_count + 1)
end

It seems like there should be a way to update the join instead of
deleting and recreating it.  I know I could always turn the join into
a model--I've done that before but it seems like overkill for
something so simple as this.  If it knows both unique ids, it should
possible.  Is there a way to update a HABTM join attribute with a
method similar to push_with_attributes?  Seems like there should be
something like:

Object.collection.update_attributes(collection_id, attribute => value)

Kevin
Mark Reginald J. (Guest)
on 2006-01-05 02:03
(Received via mailing list)
Kevin S. wrote:
> Is there a way to update attributes in a HABTM join table?  Right now  I
> am deleting the join and then recreating it with new attributes.

http://article.gmane.org/gmane.comp.lang.ruby.rails/38103


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