且构网

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

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

更新时间:2023-11-24 13:48:46

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

add_index adds an index to column specified, nothing more.

Rails 在迁移中不提供本地支持用于管理外键.此类功能包含在外国人之类的宝石中.阅读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.

强烈建议您阅读

  • http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
  • http://guides.rubyonrails.org/association_basics.html

编辑:要在评论中回答问题

To answer the question in your comment

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

belongs_to告诉rails options表中的question_id列为questions表中的记录存储了id值. 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.