add_index adds a pointer to the specified column, no more.
Rails does not provide native migration support for managing foreign keys. Such functionality is included in gems such as a foreigner . Read the documentation in which the stone is to find out how it is used.
As for associations, just add the columns that you mentioned in your Question to each table (the migration you provided looks great, maybe it is missing :rule_id ?)
Then indicate the associations in your models. To get 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 a simple (untested) start; options may not be available.
I highly recommend you read
Edit: To answer the question in your comment
class Option < ActiveRecord::Base belongs_to :question
belongs_to tells rails that the question_id column in the options table holds the id value for the entry in your questions table. Rails guesses the column name is question_id based on the character :question . You can tell rails to look at another column in the options table by specifying a parameter, for example foreign_key: :question_reference_identifier , if that was the name of the column. (Note that your Rule class in my code above uses the foreign_key parameter this way).
Your migrations are nothing more than instructions that Rails will read and execute commands in your database based on. Associations of your models ( has_many , belongs_to , etc.) inform Rails about how you want Active Record to work with your data, providing you with a simple and clear way to interact with your data. Models and migrations never interact with each other; they both interact independently with your database.
deefour Jul 12 2018-12-12T00: 00Z
source share