【问题标题】:Rails and foreign keysRails 和外键
【发布时间】:2011-12-03 03:33:17
【问题描述】:

我在 Rails 中遇到了愚蠢的魔法问题!

所以,我用外键创建了表(我正在使用 sparkfly-foreigner gem)。

class CreateCourses < ActiveRecord::Migration
  def change
    create_table :courses do |t|
      t.string :coursename,
      t.integer :subject,
      t.integer :theme,
      t.integer :hours,
      t.decimal :price,
      t.foreign_key :subject, :column => :subject, :dependent => :delete
      t.foreign_key :theme, :column => :theme, :dependent => :delete
      t.timestamps
    end
  end
end

它在终端和我的 rails webapp 中运行良好。

然后我正在创建另一个表。

class CreateGroupps < ActiveRecord::Migration
  def change
    create_table :groupps do |t|
      t.string :groupname
      t.integer :courseid
      t.integer :number,
      t.foreign_key :course, :column => :courseid, :dependent => :delete
      t.timestamps
    end
  end
end

魔法开始了。我在 Groupps 的 web 表单中写了不存在的 courseid,它在数据库中创建记录!!!当我使用终端时,我得到了这个

rails_dev=> select * from groupps
rails_dev-> ;
 id | groupname | courseid | number |         created_at         |         updated_at         
----+-----------+----------+--------+----------------------------+----------------------------
  1 | 12        |          |      1 | 2011-12-03 02:51:06.154261 | 2011-12-03 02:51:06.154261
(1 row)

rails_dev=> insert into groupps values (2,12,0,0);                                                                                                                                                          ERROR:  insert or update on table "groupps" violates foreign key constraint "groupps_courseid_fkey"
DETAIL:  Key (courseid)=(0) is not present in table "courses".

这怎么可能?当我错了?我对 rails 和 ruby​​ 太陌生了。

【问题讨论】:

    标签: ruby-on-rails ruby postgresql foreign-keys


    【解决方案1】:

    这个输出:

     id | groupname | courseid | number |         created_at         |         updated_at         
    ----+-----------+----------+--------+----------------------------+----------------------------
      1 | 12        |          |      1 | 2011-12-03 02:51:06.154261 | 2011-12-03 02:51:06.154261
    (1 row)
    

    表示您在courseid 中有一个NULL,就您的表和外键而言,这很好。您可以在引用列中包含 NULL,您可能希望将 :null =&gt; false 添加到您的 courseid

    create_table :groupps do |t|
      t.string :groupname
      t.integer :courseid, :null => false
      t.integer :number,
      t.foreign_key :course, :column => :courseid, :dependent => :delete
      t.timestamps
    end
    

    顺便说一句,由于您已经在psql 中,您可以使用\d groupps 查看表的结构、约束(包括 FK),甚至哪些 FK 引用了您的表。你可能也对\pset null感兴趣:

    null
    设置要打印的字符串以代替空值。默认是不打印任何内容,这很容易被误认为是空字符串。例如,可能更喜欢\pset null '(null)'

    【讨论】:

    • 谢谢:) 我知道解决方案一定很简单,也会有我的愚蠢错误。
    猜你喜欢
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2011-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多