【问题标题】:Rails migration issue - foreign key not getting createdRails 迁移问题 - 未创建外键
【发布时间】:2011-03-19 05:00:09
【问题描述】:

所以我有以下迁移 - 捕获 cmets 的评级(值)的典型评级表。我有一些用于主键(pk)、外键(fk)、索引(索引)的辅助方法。

所以一切运行正常,但我注意到,comment_id 上的外键没有被创建,即使这个语句没有报告错误。任何帮助,将不胜感激。谢谢。

execute("ALTER TABLE 评分添加 约束 fk_ratings_comment_id 外键(comment_id)参考 answers(id) 删除级联")

class CreateRatings < ActiveRecord::Migration

  extend MigrationHelpers

  def self.up
    create_table :ratings, :id => false do |t|
      t.integer :comment_id, :null => false
      t.integer :user_id, :null => false
      t.integer :value, :null => false, :limit => 1
      t.timestamps
    end

    pk :ratings, %w{ comment_id  user_id }
    fk :ratings, :comment_id, :comments, true
    fk :ratings, :user_id, :users
    index :ratings,  %w{ comment_id value }
  end

【问题讨论】:

    标签: mysql ruby-on-rails database migration


    【解决方案1】:

    请尝试这个而不是使用 "t.integer :comment_id, :null => false"

    t.references :table_name,:options

    【讨论】:

    • 但这不会在数据库中创建约束,它只会创建列定义。对吗?
    • 是的,这不会创建任何约束,它只会添加一个列。但是要对数据库应用约束,您需要与模型类进行交互。
    猜你喜欢
    • 1970-01-01
    • 2023-01-04
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 2015-01-13
    • 1970-01-01
    相关资源
    最近更新 更多