On Dec 22, 2007, at 6:32 PM, Philip S. wrote:
I’m wondering if anyone has suggestion on how to go about setting up a
Model that can belong to multiple tables (but only one of them).
For example, I have Companies and Contacts, both of whom can have
Notes.
However, I’d really rather not duplicate everything
I have almost exactly that.
Here’s the migration:
class CreateNotes < ActiveRecord::Migration
def self.up
create_table :notes do |t|
t.column :notable_id, :integer #required
t.column :notable_type, :string #required
t.column :created_at, :datetime
t.column :processed_by, :string, :limit => 20
t.column :body, :text
t.column :title, :string, :limit => 50
t.column :department, :string, :limit => 30
end
end
The necessary columns are the id and type.
And the Note class
class Note < ActiveRecord::Base
belongs_to :notable, :polymorphic => true
end
And then for any class you want to have notes, just make it look like
this:
class Client < ActiveRecord::Base
has_many :notes, :as => :notable
end
And that’s it. Now you can simply write something like this:
client = Client.find(1) #for example
note = Note.new
note.title = "the title"
note.body = "the body"
note.department = 'some department'
note.processed_by = current_user_name
client.notes << note
And with that last line the note is magically associated with that
client, and is part of its notes array.
other than adding the has_many :notes, :as => :notable line, you
don’t have to do anything at all to the models you want notes for.
It’s been a while since I’ve even thought about this, but I don’t
think I’ve forgotten anything.
Hope this helps.