views:

70

answers:

1

I'm a newbie to RoR - I have three models: Customer, Job and Note. Customers have Jobs, and both Customers and Jobs can have Notes. Is there a special way to handle this type of relationship in Rails, or will it work if I just have a normal belongs_to relationship with Note?

The issue that concerns me is the note having fields for both customer_id and job_id but only a single one will ever be used for a single record (i.e. a specific Note can refer to either a Job or a Customer, but never both), and it doesn't feel like good database design to have a column that will be null half of the time.

Am I over thinking this, or is there something that's not clear to me?

+4  A: 

I'd suggest using a polymorphic association as it's more flexible and expanadable, and easier to enforce. The model required is below:

class Note < ActiveRecord::Base
   belongs_to :notable, :polymorphic => true
end

class Customer < ActiveRecord::Base
   has_many :notes, :as => :notable
end

class Job < ActiveRecord::Base
   has_many :notes, :as => :notable
end

with migration

create_table :notes do |t|
  t.references :notable, :polymorphic => {:default => 'Photo'}
end

For details on a polymorphic association, I'd suggest google

workmad3
I'll take a look at Polymorphic Associations; thanks!
Wayne M
There's also a Railscast about it: http://railscasts.com/episodes/154-polymorphic-association
Jarrod
Just checked out the Railscast - this sounds like *exactly* what I need. Thanks!
Wayne M