嘿我的rake
class CreateEvents < ActiveRecord::Migration
def self.up
create_table :events do |t|
t.integer :broadcast_id
t.integer :position
t.string :title
t.string :location
t.string :link
t.text :description
t.datetime :time
end
add_foreign_key :events, :broadcast_id, :broadcasts
end
def self.down
remove_foreign_key :events, :broadcast_id, :broadcasts
drop_table :events
end
end
问题=&gt; add_foreign_key:events,:broadcast_id,:broadcasts
$ rake db:migrate
== CreateEvents: migrating ===================================================
-- create_table(:events)
-> 0.0021s
-- add_index(:events, :broadcast_id)
-> 0.0004s
rake aborted!
An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: near "FOREIGN": syntax error: ALTER TABLE "events" ADD FOREIGN KEY ("broadcast_id") REFERENCES "broadcasts"(id)
答案 0 :(得分:3)
为什么用这种方式定义外键?
如果您想要Events
和Broadcasts
之间的关系,那么您应该考虑创建一个有效的记录关系。像
# Event model
class Event < ActiveRecord::Base
belongs_to :broadcast
end
# Broadcast model
class Broadcast < ActiveRecord::Base
has_many :events
end
这样你就可以让rails为你维护外键关系。查看有关活动记录关联的Rails Guide以获取更多信息。
答案 1 :(得分:1)
从版本3.6.19开始,SQLite(也称为默认开发数据库)支持外键约束,但外键约束的强制执行turned off by default(为了向后兼容),要修复它:
建议选项:
使用其他数据库(如mysql / postgresql)作为开发 Rails中的数据库,下面是一个例子:
默认值:&amp;默认
适配器:mysql2
编码:utf8
游泳池:5
用户名:user
密码:密码
socket:/tmp/mysql.sock发展:
&lt;&lt ;: *共享
database:db_development
其他选项包括:
我们还可以通过以下命令启用外键支持:
sqlite> PRAGMA foreign_keys = ON;
sqlite> PRAGMA foreign_keys // should print 1
但请注意:
PRAGMA foreign_keys
没有打印,则表示您的SQLite版本不支持外键,请升级到3.6.19或更高版本;