Re: howto implement a join table

Ar Chron
Tue, 15 Feb 2011 18:00:13 -0000

rogi wrote in post #981715:
> Hi There
>
> I have a table for the names of my workers and a table with the
> courses they have attended.
> Now I try to create a join table to see which workers attended what
> courses.
>
Assuming you have completed something like this:
rails g scaffold worker first_name:string last_name:string
rails g scaffold course name:string description:text

(since you seem to be new to Rails, allowing Rails to generate a full
scaffolded solution is nice as an instructional tool - it gives you
something to review to see how the Rails conventions would do the
task... not that anyone leaves the scaffolded solution in place when
actually in production, but I still use it for quick brainstorming
sessions with users who have become accustomed to seeing the "ugly
scaffolded views" when testing out concepts.)

I prefer the has_many through construct, since 99.9% of the time I
always want to store some additional information in the join table, and
having to use the "proper" name for a HABTM join table - is it
worker_course or courses_workers, etc - has always irked me...

Now do:
rails g scaffold training worker_id:integer course_id:integer
  start_date:datetime end_date:datetime hours:float
rake db:migrate

in worker.rb, add
  has_many :trainings
  has_many :courses, :through => :trainings

in course.rb, add
  has_many :trainings
  has_many :workers, :through => :trainings

in training.rb, add
  belongs_to :worker
  belongs_to :course

should get you going from the data perspective. A partial displaying the
training for a worker would be good, as would a partial for a course
showing the trainings.

--
Posted via http://www.ruby-forum.com/.