has_many, belongs_to relation in active record migration rails 4

前端 未结 6 1674
粉色の甜心
粉色の甜心 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条回答
  •  Happy的楠姐
    2020-12-12 16:18

    You could call:

    rails g model task user:references
    

    which will generates an user_id column in the tasks table and will modify the task.rb model to add a belongs_to :user relatonship. Please note, you must to put manually the has_many :tasks or has_one :task relationship to the user.rb model.

    If you already have the model generated, you could create a migration with the following:

    rails g migration AddUserToTask user:belongs_to
    

    which will generate:

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

    the only difference with this approach is, the belongs_to :user relationship in the task.rb model won't be created automatically, so you must create it for your own.

提交回复
热议问题