Maayan Naveh
Maayan Naveh

Reputation: 370

Adding one-to-many association on namespaced models

I'm trying to set up a one-to-many relationship between two namespaced models, and despite my best efforts can't catch where my problem is.

Here is my migration:

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 model:

class Admin::Plan < ApplicationRecord
   belongs_to :course, class_name: 'Academy::Course', optional: true, foreign_key: :academy_courses_id
end

Academy::Course model:

class Academy::Course < ApplicationRecord
   has_many :plans, class_name: 'Admin::Plan, foreign_key: :admin_plans_id
end

Here's what happens when I try to get all plans for a course:

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>

I'd really appreciate ideas of where this admin_plans.course_id is coming from, since I declared that the foreign key is :academy_courses_id. Thanks :)

Upvotes: 0

Views: 50

Answers (1)

Maayan Naveh
Maayan Naveh

Reputation: 370

After a lot of banging my head on the wall and trying every method on Google, I settled for this:

Migration:

   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:

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

Upvotes: 0

Related Questions