【问题标题】:t.references in Rails migration (n | n relationship)Rails 迁移中的 t.references(n | n 关系)
【发布时间】:2012-12-13 05:43:35
【问题描述】:

我的 Rails 3 应用程序中有三个模型,DailyDataDailyDataVehicleVehicle,多对多关系。

我刚刚了解到,如果您使用关联更新模型,它不会更新数据库,因此我将返回并添加这些迁移。我也很幸运地自信地认为我知道belongs_tohas_many 之间的区别,但是,在我的迁移文件中,我不确定t.references 是否知道。
所以我将迁移模型命名为AddDailyDataToDailyDataVehicle,并希望将dailyData_id 添加到daily_data_vehicles 表中。这是一个多对多关系,所以我希望 id key 出现在关系表 DailyDataVehicles 中,但我不太确定 t.references 会知道这一点。
也许我稍微混淆了类关联和数据库关系,如果是,请澄清这一点。
如果t.references不是我想要的,我是否必须手动声明与has_many的关系,如果是,那么它的语法是什么?

当前架构文件:

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"

迁移(尝试):

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

如果迁移正常,我认为架构文件应该是什么样子:

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"

区别在于t.integer "dailyData_id"add_index "daily_data_vehicles", ["dailyData_id"], :name =&gt; "index_daily_data_vehicles_on_daily_data_id"

【问题讨论】:

  • 只有在你的架构文件中才会这样
  • 所以 t.references 会解决架构方面的问题吗?然后我也必须相应地调整模型?

标签: ruby-on-rails ruby-on-rails-3 relationship has-many belongs-to


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-11-08
    • 1970-01-01
    • 2012-06-08
    • 2014-07-08
    相关资源
    最近更新 更多