且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

rails (3.2) 中的关联和(多个)外键:如何在模型中描述它们,并写出迁移

更新时间:2023-11-24 13:49:04

add_index 添加索引到指定的列,仅此而已.

add_index adds an index to column specified, nothing more.

Rails 在迁移中不提供本机支持用于管理外键.此类功能包含在 foreigner 之类的 gem 中.阅读 gem 的文档以了解它是如何使用的.

Rails does not provide native support in migrations for managing foreign keys. Such functionality is included in gems like foreigner. Read the documentation that gem to learn how it's used.

至于关联,只需将您在问题中提到的列添加到每个表中(您提供的迁移看起来不错;也许缺少 :rule_id?)

As for the associations, just add the columns you mentioned in your Question to each table (the migration you provided looks fine; maybe it's missing a :rule_id?)

然后在您的模型中指定关联.让你开始

Then specify the associations in your models. To get you started

class Question < ActiveRecord::Base
  has_many :options
  has_many :assumption_rules, class_name: "Rule"
  has_many :consequent_rules, class_name: "Rule"
end

class Rule < ActiveRecord::Base
  belongs_to :option
  belongs_to :assumption_question, class_name: "Question", foreign_key: :assumption_question_id, inverse_of: :assumption_rules
  belongs_to :consequent_question, class_name: "Question", foreign_key: :consequent_question_id, inverse_of: :consequent_rules
end

class Option < ActiveRecord::Base
  belongs_to :question
  has_one    :rule
end

注意这只是一个(未经测试)的开始;可能缺少选项.

Note This is just a (untested) start; options may be missing.

强烈推荐你阅读

回答评论中的问题

class Option < ActiveRecord::Base
  belongs_to :question
  # ...

belongs_to 告诉 rails options 表中的 question_id 列存储记录的 id 值在您的 questions 表中.Rails 根据 :question 符号猜测列的名称是 question_id.您可以通过指定像 foreign_key::question_reference_identifier 这样的选项来指示 rails 查看 options 表中的不同列,如果这是列的名称.(注意我上面代码中的 Rule 类以这种方式使用了 foreign_key 选项).

The belongs_to tells rails that the question_id column in your options table stores an id value for a record in your questions table. Rails guesses the name of the column is question_id based on the :question symbol. You could instruct rails to look at a different column in the options table by specifying an option like foreign_key: :question_reference_identifier if that was the name of the column. (Note your Rule class in my code above uses the foreign_key option in this way).

您的迁移只不过是 Rails 将根据您的数据库读取和执行命令的指令.您的模型关联(has_manybelongs_to 等...) 通知 Rails 您希望 Active Record 如何处理您的数据,为您提供了一种与数据交互的清晰而简单的方式.模型和迁移永远不会相互交互;它们都独立地与您的数据库交互.

Your migrations are nothing more than instructions which Rails will read and perform commands on your database based from. Your models' associations (has_many, belongs_to, etc...) inform Rails as to how you would like Active Record to work with your data, providing you with a clear and simple way to interact with your data. Models and migrations never interact with one another; they both independently interact with your database.