views:

22

answers:

1

This is probably pretty simple, but here:

Say I've got two models, Thing and Tag

class Thing < ActiveRecord::Base
    has_and_belongs_to_many :tags
end

class Tag < ActiveRecord::Base
    has_and_belongs_to_many :things
end

And I have an instance of each. I want to link them. Can I do something like:

@thing = Thing.find(1)
@tag = Tag.find(1)

@thing.tags.add(@tag)

If not, what is the best way to do this? Thanks!

+1  A: 

I think the best way is to use find_or_create.

tag = @thing.tags.find_or_create_by_name('tagname')
Antiarchitect