has_many, belongs_to relation in active record migration rails 4

前端 未结 6 1670
粉色の甜心
粉色の甜心 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 15:59

    The Relationship in Rails is taken care by model not by Rails.

    So you just need to define this relationship in your model:

    class User < ActiveRecord::Base
      has_many :tasks
    end
    
    class Task < ActiveRecord::Base
      belongs_to :user
    end
    

    And just make sure that a user_id field is present in the migration for creating the "tasks" table.

提交回复
热议问题