ActiveRecord Noob

"Hi everyone. My name is Chris, and I'm an ActiveRecord noob."

I've been avoiding adding "tags" to my posts due to my perceived complexity of how to achieve this with  ActiveRecord.  Funnily enough, this was pathetically simple, so simple it made realize that I know very little about ActiveRecord.

Expressing, well actually using, a many to many relationship is intuitive. I have a Post class and I have a Tag class, each maps to a table with the same name.  They are associated to each other like this:

[ActiveRecord]
public class Tag : ActiveRecordBase {
    private IList _tags;
    [HasAndBelongsToMany(typeof(Tag), 
    	Table = "post_tag", 
    	ColumnRef = "tag_id", 
    	ColumnKey = "post_id")]
    public IList Tags {
    	get	{
    		return _tags;
    	}
    	set	{
    		_tags = value;
    	}
    }
}

[ActiveRecord]
public class Post : ActiveRecordBase {
    private IList _posts;
    [HasAndBelongsToMany(typeof(Post), 
    	Table = "post_tag", 
    	ColumnRef = "post_id", 
    	ColumnKey = "tag_id")]
    public IList Posts{
    	get	{
    		return _posts;
    	}
    	set	{
    		_posts = value;
    	}
    }
}

There is an association table named post_tag that just has the columns post_id and tag_id.  I never touch this, ActiveRecord and NHibernate take care of the details.  When I roll my own sql code, I usually end up deleting all associated tags with a post, and then adding back just the tags that are currently associated with the post.  ActiveRecord let's me do essentially the same thing but I just use the objects.  The following code does essentially the same thing:

post.Tags.Clear();
bool createIfNotFound = true;
post.Tags.Add(Tag.FindByName("JavaScript", createIfNotFound));
post.Save();

 
Author: , 0000-00-00