you need
has_and_belongs_to_many http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M001888&name=has_and_belongs_to_many
How, precisely will a join-table help, when he says that "Normalizing
the DB is out of the question"?
:-/
Hi,
Working with legacy DB here...
2 tables:
Projects
Workers
A worker record has many fields in it to hold project codes as in:
project1, project2, project3, ... project30 (great, isn't it?...)
Normalizing the DB is out of the question.
I've been thinking about this for a while and I can't find a way to
associate both tables as in:
"Project has_many :workers"
"Worker.project1 belongs_to :project"
"Worker.project2 belongs_to :project"
etc.
You are highly limited given your inability to re-structure the
database, and I wonder whether you want to reconsider negotiation with
whatever powers that be to refactor the database a little (or a lot!
But working with the tables you have, you can at least use AR as much
as possible...
# worker model
belongs_to :project1, :class_name => "Project", :foreign_key =>
"project1_foreign_key_name_in_workers_table"
belongs_to :project2, :class_name => "Project", :foreign_key =>
"project2_foreign_key_name_in_workers_table"
belongs_to :project3, :class_name => "Project", :foreign_key =>
"project3_foreign_key_name_in_workers_table"
The project model is going to be harder, and you're not going to be
able to intuitively assign workers to projects, but you can at least
fudge-together some helper methods to make it look like you're
leveraging the power of Rails!
#project model
has_many :project1_keyed_workers, :class_name => "Worker",
:foreign_key => "project1_foreign_key_name_in_workers_table"
has_many :project2_keyed_workers, :class_name => "Worker",
:foreign_key => "project2_foreign_key_name_in_workers_table"
has_many :project3_keyed_workers, :class_name => "Worker",
:foreign_key => "project3_foreign_key_name_in_workers_table"
def workers
# build and array of all the arrays of workers, flatten it and get
rid of nil values
( << project1_keyed_workers << project2_keyed_workers <<
project3_keyed_workers).flatten.compact
end
Hope this helps....
Michael