使用以下方式创建模型:
rails g model Product product_name:string
rails g model ProductCategory category_name:string
class Product < ActiveRecord::Base
belongs_to :product_category
end
class ProductCategory < ApplicationRecord
has_many :products
end
如何将类别ID(ProductCategory)引用到产品中? 我在下面编辑和编辑迁移:
class AddProductCategoryToProducts < ActiveRecord::Migration[5.0]
def change
product_category = ProductCategory.create! category_name: "No category"
add_reference :products, :product_category, foreign_key: true, default: product_categories_id
end
end
之后我运行rake db:migrate并收到错误:
== 20160716050030 AddCourseCategoryToCourses: migrating =======================
-- course_categories_id()
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
undefined local variable or method `course_categories_id' for #<AddCourseCategoryToCourses:0x007fabfd2667d0>