Take the 2-minute tour ×

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

class Tag < ActiveRecord::Base
    has_and_belongs_to_many :things

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)


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

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

I think the best way is to use find_or_create.

tag = @thing.tags.find_or_create_by_name('tagname')
share|improve this answer
add comment

Your Answer


