Relation attributes

Posted by tom February 21st, 2006

Found an interesting piece of text concerning relation attributes on the rails mailing list.

User: 
  has_many :bookmarks 

Bookmarks: 
  belongs_to :user 
  belongs_to :site 
  has_and_belongs_to_many :tags 

Site: 
  has_many :bookmarks 

Tags: 
  has_and_belongs_to_many :bookmarks 
You would need the following tables:
  users 
  bookmarks < < (has a user_id and site_id foreign key)(this could also 
have a rank field) 
  sites 
  tags 
  bookmarks_tags < < (bookmark_id and tag_id foreign key) 
In rails you will then be able to do the following:

  @user = User.find(:first) 
  @user.bookmarks (returns list of bookmarks for this user) 

  @bookmark = Bookmark.find(:first) 
  @bookmark.tags (returns a list of tags) 

  @tag = Tag.find(:first) 
  @tag.bookmarks (returns list of bookmarks for this tag) 

  @site = Site.find(:first) 
  @site.bookmarks (returns list of bookmarks for this site) 
Original reply can be found here.

Leave a Reply