From: Lake Denman Date: 2008-08-12T05:58:40+09:00 Subject: Re: How to map this association Hi Wenhan, This is how I set up my association and I think it works well... I'm using has_many through instead of has_and_belongs_to_many. I think that using has_many through is now more widely accepted than it's predecessor. Anyways, on to the show. Here's what we have: Models User: has_many :videos, :foreign_key=>'added_by' # in retrospect that might not be the best name. You could try contributor_id, maybe. has_many :video_collections has_many :collected_videos, :through=>:video_collections, :source=>:video # We have to specify a source since we aren't really following the naming convention. Video: belongs_to :user, :foreign_key=>'added_by' has_many :video_collections has_many :collectors, :through=>:video_collections,:source=>:user VideoCollection: belongs_to :user belongs_to :video Next up, Simple Migrations for the Models! Users class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.string :name t.timestamps end User.create!(:name=>"Lake") end def self.down drop_table :users end end Videos class CreateVideos < ActiveRecord::Migration def self.up create_table :videos do |t| t.string :title t.integer :added_by t.timestamps end Video.create!(:title=>"Gone With The Wind", :added_by=>1) end def self.down drop_table :videos end end Video Collections (rumor has it that you can pass :id=>false here, but I forgot to do that when I generated this) class CreateVideoCollections < ActiveRecord::Migration def self.up create_table :video_collections do |t| t.integer :user_id t.integer :video_id t.timestamps end VideoCollection.create!(:user_id=>1, :video_id=>1) end def self.down drop_table :video_collections end end Okay, so we have our migrations setup and the next thing we cna do is Migrate: rake db:create:all;rake db:migrate Then fire up the script/console in your rails_root directory: ruby script/console Let's see what happens (ps. We already created some rows in the migrations): #Make sure all our entities are there: >> User.find(1) => # >> Video.find(1) => #