开发者

if using a join table, does the relationship have to be HABTM?

I have Worker, Manager, and Title models in Rails 2.x. There is also a JOIN table that has only worker_id, manager_id, and title_id (no explicit model for this). Because of this JOIN table (and not having a model for it), I assume I have to have the following:

In the Worker model, I have:

Worker
has_and_belongs_to_many :managers
has_and_belongs_to_many :titles

But, in reality, the relationship is that Worker can only have 1 Manager, but many Titles. Also, many Workers have the same Manager.

Some sample data to illustrate the relationship:

Worker | Title | Manager
Tom    | A     | M1
Tom    | B     | M1
Bob    | A     | M2
Pam    | C     | M1
开发者_运维百科

Is the above Worker model "correct"? When creating a new Worker (and all their relationships), I do:

worker = Worker.new("A")
title = "B"
manager = "C"
worker.titles << title
worker.managers << manager
worker.save

When I do this, I get the following in my database:

Worker | Title | Manager
A      | B     | null
A      | null  | C

I would like to get:

Worker | Title | Manager
A      | B     | C


You can move the manager_id (since, a Worker can have only on Manager) and have the relationships like this

class Manager < AR::Base
  has_many :workers
end

Then, in the Worker belongs_to a Manager.

class Worker < AR::Base
  belongs_to :manager
end

You need to have a join table, like "workers_titles" for hold the relationships between workers and titles

create_table "workers_titles", :id => false do |t|
  t.column "worker_id", :integer, :null => false
  t.column "title_id",  :integer, :null => false
end

Models:

class Worker < AR::Base
  has_and_belongs_to_many :titles
end

class Title < AR::Base
  has_and_belongs_to_many :workers
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜