Search code examples
ruby-on-railsruby-on-rails-3relationshiphas-manybelongs-to

t.references in Rails migration (n | n relationship)


I have three models in my Rails 3 application, DailyData and DailyDataVehicle and Vehicle, a many to many relationship.

I just learned that if you update the model with the associations, that it doesn't update the database, so I am going back and adding those migrations. I am also lucky enough to confidently think I know the differences between belongs_to and has_many, however, in my migration file, I am not sure that t.references does.
So I named the migration model AddDailyDataToDailyDataVehicle, and want to add the dailyData_id to the daily_data_vehicles table. This is a many to many relationship, so I want the id key to be in the relationship table DailyDataVehicles, but I'm not quite sure that t.references will know that.
Maybe I am slightly mixing up the class associations and the database relationships, and if I am, then please clarify this.
If t.references is not what I want, do I have to declare the relationship manually with has_many, and if so, what is the syntax for that?

schema file currently:

create_table "daily_data_vehicles", :force => true do |t|
  t.integer  "vehicle_id"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end
add_index "daily_data_vehicles", ["vehicle_id"], :name => "index_daily_data_vehicles_on_vehicle_id"

Migration (attempt):

class AddDailyDataToDailyDataVehicle < ActiveRecord::Migration
  def change
    change_table :dailyDataVehicles do |t|
      t.references :dailyData
    end
    add_index :dailyDataVehicles, :dailyData_id
  end
end

What I think the schema file should look like if the migration works correctly:

create_table "daily_data_vehicles", :force => true do |t|
  t.integer  "vehicle_id"
  t.integer  "dailyData_id"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end
add_index "daily_data_vehicles", ["vehicle_id"], :name => "index_daily_data_vehicles_on_vehicle_id"
add_index "daily_data_vehicles", ["dailyData_id"], :name => "index_daily_data_vehicles_on_daily_data_id"

with the difference being t.integer "dailyData_id" and add_index "daily_data_vehicles", ["dailyData_id"], :name => "index_daily_data_vehicles_on_daily_data_id"


Solution

  • class AddDailyDataToDailyDataVehicle < ActiveRecord::Migration
      def change
        add_column :daily_data_vehicles, : daily_data_id, :integer
        add_index :daily_data_vehicles, :daily_data_id
      end
    end
    
    class DailyDataVehicle < ActiveRecord::Base
      belongs_to :daily_data
    end
    
    class DailyData < ActiveRecord::Base
      has_many :daily_data_vehicles
    end