我试图在两个命名空间模型之间建立一对多关系,尽管我尽了最大努力也无法捕捉到问题所在。
这是我的移民:
class AddAssociations < ActiveRecord::Migration[5.1]
def change
add_belongs_to :admin_plans, :academy_courses, foreign_key: true, index: true
add_reference :academy_courses, :admin_plans, foreign_key: true, index: true
end
end
Admin::Plan
模型:
class Admin::Plan < ApplicationRecord
belongs_to :course, class_name: 'Academy::Course', optional: true, foreign_key: :academy_courses_id
end
Academy::Course
模型:
class Academy::Course < ApplicationRecord
has_many :plans, class_name: 'Admin::Plan, foreign_key: :admin_plans_id
end
当我尝试获得课程的所有计划时,会发生以下情况:
irb(main):001:0> c = Academy::Course.new
=> #<Academy::Course id: nil, title: nil, description: nil, user_id: nil, created_at: nil, updated_at: nil, admin_user_plans_id: nil, admin_plans_id: nil>
irb(main):004:0> c.plans
=> #<ActiveRecord::Associations::CollectionProxy []>
irb(main):005:0> c.plans.all
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedColumn: ERROR: column admin_plans.course_id does not exist)
LINE 1: SELECT "admin_plans".* FROM "admin_plans" WHERE "admin_plan...
^
: SELECT "admin_plans".* FROM "admin_plans" WHERE "admin_plans"."course_id" = $1 LIMIT $2
irb(main):007:0> Admin::Plan.last
Admin::Plan Load (1.0ms) SELECT "admin_plans".* FROM "admin_plans" ORDER BY "admin_plans"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Admin::Plan id: 2, name: "MOMLab", price: 15, created_at: "2019-02-06 15:05:43", updated_at: "2019-02-07 07:12:26", academy_courses_id: nil>
我非常感谢有关admin_plans.course_id来自何处的想法,因为我宣布外键为:academy_courses_id
。
谢谢:)
答案 0 :(得分:0)
在将头撞到墙上并尝试了Google上的各种方法之后,我为此解决了:
迁移:
class AddCourseIdToAcademyLessons < ActiveRecord::Migration[5.1]
def change
add_column :admin_plans, :course_id, :integer, foreign_key: true, index: true
end
end
Admin :: Plan类:
class Admin::Plan < ApplicationRecord
belongs_to :course, class_name: 'Academy::Course', optional: true
end
Academy :: Course class:
class Academy::Course < ApplicationRecord
has_many :plans, class_name: 'Admin::Plan'
end