1

I am new to ruby on rails. I have created a many-to-many association and a migration, such as follows:

in Foo model:

has_and_belongs_to_many bars

in Bar model:

has_and_belongs_to_many foos

and the migration for join table has the following content:

def change
  create_table :foos_bars, id: false do |t|
    t.references :foo
    t.references :bar
  end
end

Now I see that the association should be one-to-many as: foo has many bars. I don't know if I have generated controllers after the above migration, but I know that the file of the above migration is the last one that was created in the migrate folder. Also I have not made any connection yet between any foo and any bar.

Can I do the following to start fresh (change the association and also remove the file of the migration):

  1. use 'rake db:rollback'

  2. delete the file of the join table migration (i.e. timestamp_create_bars_foos.rb file)

  3. change the 'has_and_belongs_to_many' in foo to 'has_many', and in bar to 'belongs_to'

  4. run: 'rails generate migration CreateFoosBars'

  5. run: 'rake db:migrate'

If not, what can I do to make the above modification for the association?

Thanks in Advance!

Prakash Murthy
  • 12,355
  • 3
  • 38
  • 66
Cror2014
  • 317
  • 2
  • 14

1 Answers1

0

The steps you have listed looks good.

The only thing that stands out is the intention to CreateFoosBars again in Step 4 : rails generate migration CreateFoosBars'.

Since the foos and bars tables are already created, and this is a has_many relationship, you just need to add a reference for foo in the bars table, and not create a new table.

Something along the lines of:

rails g migration add_foo_id_to_bar foo_id:integer

Would advise reviewing Rails 3 migrations: Adding reference column? to figure out what the migration should do.

Community
  • 1
  • 1
Prakash Murthy
  • 12,355
  • 3
  • 38
  • 66