I have a pretty simple HABTM set of models
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
This is really old but I thought I'd share my way of doing this.
class Tag < ActiveRecord::Base
has_and_belongs_to_many :posts
end
class Post < ActiveRecord::Base
has_and_belongs_to_many :tags
end
In the code where I need to add tags to a post, I do something like:
new_tag = Tag.find_by(name: 'cool')
post.tag_ids = (post.tag_ids + [new_tag.id]).uniq
This has the effect of automatically adding/removing tags as necessary or doing nothing if that's the case.