has_many, belongs_to relation in active record migration rails 4

前端 未结 6 1678
粉色の甜心
粉色の甜心 2020-12-12 15:28

I have a User model and a Task model. I have not mentioned any relation between them while creating them.

I need to establish that U

6条回答
  •  情话喂你
    2020-12-12 16:00

    To answer the question, "What would be the migration generation command for establishing that relation?"( Meaning, how do you add a migration for existing models with a relationship like User has_many Tasks & Task belongs_to User)

    The the easiest way for me to remember is like this:

    >rails g migration AddUserToTask user:belongs_to
    

    or

    >rails g migration AddUserToTask user:references
    

    :belongs_to is just an alias of :references, so either will do the same thing.

    Doing it this way, the command will infer the name of the table from the migration name, set up a change method that will add the column for relationship, and configure it to be indexed:

    class AddUserToTask < ActiveRecord::Migration
      def change
        add_reference :tasks, :user, index: true
      end
    end
    

    After generating that you:

    >rake db:migrate
    

    Finally, you still have to add the usual relations to your models, as is stated in the other answers, but I think this is the right answer to your question.

提交回复
热议问题