Foreign key in rails 4

独自空忆成欢 提交于 2019-12-23 09:36:38

问题


I'm using Rails 4 and SQLite. I'm trying to add foreing keys to my indicators table. Please see my code below

class Indicator < ActiveRecord::Base
  belongs_to :objetive
  belongs_to :responsible, class_name: "Person"

end

The migration script:

class AddFksToIndicator < ActiveRecord::Migration
  def change
      add_reference :indicators, :objective, index: true
      add_reference :indicators, :responsible, index: true
  end
end

when run the migration all is ok, so I tried in console:

2.0.0p247 :002 > i = Indicator.new
 => #<Indicator id: nil, name: nil, created_at: nil, updated_at: nil, objective_id: nil, responsible_id: nil> 
2.0.0p247 :002 > i.objective_id = 0
2.0.0p247 :003 > i.save

To my surprise, the indicator was saved and there is no obective with id = 0.

Finally, I checked the indicators table schema and I get:

CREATE TABLE "indicators" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "created_at" datetime, "updated_at" datetime, "objective_id" integer, "responsible_id" integer);
CREATE INDEX "index_indicators_on_objective_id" ON "indicators" ("objective_id");
CREATE INDEX "index_indicators_on_responsible_id" ON "indicators" ("responsible_id");

Why there is no foreign key constraint on objective_id and responsible_id? Am I doing something wrong?


回答1:


According to Ruby on Rails 4.2 Release notes, only the mysql, mysql2 and postgresql adapters support foreign keys.

Unfortunately, the sqlite3 adapter does not.




回答2:


When you're using add_reference, you'd need to add foreign_key: true to to get foreign key support with that call. For example:

add_reference :indicators, :objective, index: true, foreign_key: true

The default is foreign_key: false, as mentioned in the docs here.

Since you've already created your migration without a foreign key, you'll need to create another migration with a call to add_foreign_key.

For example:

def change
   # add_foreign_key(from_table, to_table)
   add_foreign_key :indicators, :objectives
end

Here's the documentation for add_foreign_key.

Hope this helps.



来源:https://stackoverflow.com/questions/17956204/foreign-key-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!