我不希望使用NULL作为外键的模型属于任何东西!
我有以下rails应用程序,模拟蚂蚁和蚂蚁山(灵感来自Jozef).
$ rails -v
Rails 3.2.8
$ rails new ant_hill
$ cd ant_hill
Run Code Online (Sandbox Code Playgroud)
创建蚂蚁山和蚂蚁模型.蚂蚁可以属于蚂蚁山,蚂蚁山可以有许多蚂蚁.
$ rails generate model AntHill name:string
$ rails generate model Ant name:string ant_hill_id:integer
$ vim app/models/ant.rb
$ cat app/models/ant.rb
class Ant < ActiveRecord::Base
belongs_to :ant_hill
end
$ vim app/models/ant_hill.rb
$ cat app/models/ant_hill.rb
class AntHill < ActiveRecord::Base
has_many :ants
end
$ rake db:migrate
== CreateAntHills: migrating =================================================
-- create_table(:ant_hills)
-> 0.0013s
== CreateAntHills: migrated (0.0016s) ========================================
== CreateAnts: migrating =====================================================
-- create_table(:ants)
-> 0.0035s
== CreateAnts: …Run Code Online (Sandbox Code Playgroud) activerecord ruby-on-rails foreign-keys has-many relationship