t.belongs_to in migration

前端 未结 6 1296
攒了一身酷
攒了一身酷 2020-12-25 10:31

I was using Ryan Bates\'s source code for railscasts #141 in order to create a simple shopping cart. In one of the migrations, he lists

class CreateProducts         


        
6条回答
  •  情话喂你
    2020-12-25 10:58

    First: the migration

    rails generate migration add_user_to_products user:belongs_to

    (in this situation) is equivalent to

    rails generate migration add_user_to_products user:references

    and both create

    class AddUserToProducts < ActiveRecord::Migration
      def change
        add_reference :products, :user, index: true
      end
    end
    

    You could 'read' add_reference :products, :user, index: true as "products belong to user(s)"

    In the schema, the migration will create a field in the items table called "user_id". This is why the class is called AddUserToProducts. The migration adds the user_id field to products.

    Second: the model

    He then should have updated the product model as that migration would have only changed the schema. He would have had to update the user model too with something like

    class User < ActiveRecord::Base
     has_many :products
    end
    

    In general

    rails g migration add_[model linking to]_to_[table containing link] [model linking to]:belongs_to

    Note: g is short for generate

    class User < ActiveRecord::Base
     has_many :[table containing link]
    end
    

提交回复
热议问题