如何在模型之间生成关联

Mar*_*ark 20 ruby-on-rails activemodel ruby-on-rails-3.1

我想知道如何在Rails中正确地进行关联.首先,我创建了一个城市模型和一个组织.现在我希望组织有一个城市...这是通过添加has_manyhas_one关联来完成的.之后我跑了rake db:migrate.但不知何故,它不会创建一个字段citycity_id在我的数据库模型中.我自己必须这样做吗?rails现在不应该在数据库中创建外键约束吗?

要查看它是否有效我正在使用rails c并输入Organisation 答案如下:

=> Organisation(id: integer, name: string, description: string, url: string, created_at: datetime, updated_at: datetime) 
Run Code Online (Sandbox Code Playgroud)

请原谅我的愚蠢问题......我是Rails的初学者,一切都还是很陌生.

谢谢!


市:

class City < ActiveRecord::Base
  has_many :organisations
end
Run Code Online (Sandbox Code Playgroud)

组织:

class Organisation < ActiveRecord::Base
  has_one :city
end
Run Code Online (Sandbox Code Playgroud)

创建城市:

class CreateCities < ActiveRecord::Migration
  def change
    create_table :cities do |t|
      t.string :name
      t.string :country

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

创建组织:

class CreateOrganisations < ActiveRecord::Migration
  def change
    create_table :organisations do |t|
      t.string :name
      t.string :description
      t.string :url

      t.timestamps
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

Fee*_*ech 19

这有几个问题.

  1. 您需要belongs_to在一个has_manyhas_one关联的另一侧指定一个.定义belongs_to关联的模型是外键所属的位置.

    因此,如果一个组织has_one :city,那么一个城市需要belongs_to :organization.或者,如果是一个城市has_one :organization,那么组织需要belongs_to :city.

    查看您的设置,看起来您想要belongs_toCity模型中定义.

  2. 迁移不是基于模型定义构建的.相反,它们是从db/migrations文件夹构建的.运行rails g model命令(或rails g migration)时会创建迁移.为了获得外键,您需要告诉生成器创建它.

    rails generate model organization name:string description:string url:string city_id:integer
    
    Run Code Online (Sandbox Code Playgroud)

    要么

    rails generate model city name:string description:string url:string organization_id:integer
    
    Run Code Online (Sandbox Code Playgroud)