我需要有“参考资料”吗?我的问题和答案模型中的列?

发布于 2024-08-06 23:30:33 字数 742 浏览 0 评论 0原文

如果问题和答案之间存在 has_manybelongs_to 关系:

class Question < ActiveRecord::Base
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
end

我是否还需要修改迁移文件以使用“引用”:

class CreateAnswers < ActiveRecord::Migration
  def self.up
    create_table :answers do |t|
      t.text :body
      t.references :question

      t.timestamps
    end
  end

  def self.down
    drop_table :answers
  end
end

class CreateQuestions < ActiveRecord::Migration
  def self.up
    create_table :questions do |t|
      t.text :body
      t.references :answer

      t.timestamps
    end
  end

  def self.down
    drop_table :questions
  end
end

If I have a has_many and belongs_to relationship between Questions and Answers:

class Question < ActiveRecord::Base
  has_many :answers
end

class Answer < ActiveRecord::Base
  belongs_to :question
end

Do I also need to modify the migration files to use "references":

class CreateAnswers < ActiveRecord::Migration
  def self.up
    create_table :answers do |t|
      t.text :body
      t.references :question

      t.timestamps
    end
  end

  def self.down
    drop_table :answers
  end
end

class CreateQuestions < ActiveRecord::Migration
  def self.up
    create_table :questions do |t|
      t.text :body
      t.references :answer

      t.timestamps
    end
  end

  def self.down
    drop_table :questions
  end
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小…红帽 2024-08-13 23:30:33

外键仅出现在属于另一个的模型中。

The foreign key only goes in the model that belongs_to the other.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文