无法通过在rails上使用下划线(product_order)来获取引用ID

时间:2016-07-16 07:13:07

标签: ruby-on-rails activerecord reference foreign-keys migration

使用以下方式创建模型:

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>

0 个答案:

没有答案