向现有的Rails模型添加模型参考 [英] Adding a Model Reference to existing Rails model

查看:128
本文介绍了向现有的Rails模型添加模型参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Rails 3的两个现有类之间添加关系的正确"方法.

I'd like to know the "proper" way to approach adding a relation between two existing classes in Rails 3.

考虑到现有的型号:Clown&兔子

Given existing models: Clown & Rabbit

我想添加一个从Rabbit到Clown的引用(属于).我首先尝试生成迁移:

I'd like to add a reference (belongs_to) from Rabbit to Clown. I start by trying to generate a migration:

rails g migration AddClownToRabbits clown:reference

这使我的迁移看起来像:

which gives me a migration that looks like:

class AddClownToRabbits < ActiveRecord::Migration
  def self.up
    add_column :rabbits, :clown, :reference
  end

  def self.down
    remove_column :rabbits, :clown
  end
end

在此迁移中,在rake db:migrate之后,我检查了SQLite3的development.db并看到了新列:"clown" reference

After rake db:migrate on this migration I examine SQLite3's development.db and see a new column: "clown" reference

我想我期望有一个"clown_id" integer列和一个看起来像这样的迁移:

I guess I was expecting a "clown_id" integer column and a migration that looked like:

class AddClownToRabbits < ActiveRecord::Migration
  def self.up
    add_column :rabbits, :clown_id
  end

  def self.down
    remove_column :rabbits, :clown_id
  end
end

我确定:reference应该等效于"t.references:clown",但是我找不到文档(非常惊讶). API说add_column:Instantiates a new column for the table. The type parameter is normally one of the migrations native types, which is one of the following: :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.

I'm sure :reference is supposed to be equivalent to "t.references :clown" but I can't find the documentation (big surprise). API says add_column: Instantiates a new column for the table. The type parameter is normally one of the migrations native types, which is one of the following: :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.

...没有对 reference .

推荐答案

在Rabbit中设置"belongs_to",在小丑"中设置has_many之后,您可以使用以下方法进行迁移:

After you set belongs_to in Rabbit, and has_many in Clown, you can do a migration with:

add_column :rabbit, :clown_id, :integer

这篇关于向现有的Rails模型添加模型参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆