How to delete join table?

Hi -

I have a join table that joins a people table and a roles table. It’s
configured using the has_and_belongs_to_many statement in the model

How do I delete the join table? I have code that migrates from a legacy
db into my rails db, and as part of the migration I want to delete the
people, roles, and people_roles tables to start with a clean db. It’s
easy to delete the people table with Person.delete_all and likewise with
the roles table. But the join table gets left behind. How would I
delete the people_roles table?


If you had a model instead of a has_and_belongs_to_many, you could do

has_many :people_roles
has_many :roles, :through => :people_roles

has_many :people_roles
has_many :roles, :through => :people_roles

belongs_to :person
belongs_to :role

And then you can call PeopleRole.delete_all.

On Mon, May 19, 2008 at 9:15 AM, Steven L. <
[email protected]> wrote:

db into my rails db, and as part of the migration I want to delete the

Ryan B.

Feel free to add me to MSN and/or GTalk as this email.

Thanks! I figured out another way, involving some trickery. Your way
is probably more recommended.

I created a model named people_role.rb. Note the first part of the name
is the plural form of Person, and the second part is the singular of the
Role table. I did that because rails will pluralize the word
people_role into people_roles, and people_roles is the name of my table.

Then I can call PeopleRole.delete_all and it appears to work.

Hmm, ran into a glitch further down the road so I redid everything your
way and that works better.

For some reason each join table row had it’s own id. In this case the
join table columns were role_id, person_id, and id. My problem was that
when saving each join table row, it was setting the id to the role_id,
and since my role_id’s weren’t unique within the join table, the saves
were failing. I have no idea why it was doing that.

Probably due to you creating the table like this:

create_table :people_roles do |t|
t.references :person, :role


t.integer :person_id, :role_id

instead of create_table :people_roles, :id => false which would not put
that id column automatically.

What was the exact error you were getting and what code were you using
get it? You should be able to assign many roles to many people and
vice-versa ad infinitum ergo (and any other trippy words)

Hmm, I don’t really have the code available, I’ve changed it.

Thanks for your help. It was very good.

interesting . . . next question then, why when I save a person with a
role would active record be setting the id of the join row to the
role_id? Since I reuse roles I was getting constraint violation type
errors because it was trying to save a people_roles row the the same id
as another row.