1

This is on rails 4.2.11.3. I have a has_many through relationship set up like this:

class ProgramCourse < ActiveRecord::Base
  belongs_to :course
  belongs_to :program
end

class Course < ActiveRecord::Base
  has_many :program_courses
  has_many :programs, -> { uniq }, through: :program_courses
end

class Program < ActiveRecord::Base
  has_many :program_courses
  has_many :courses, -> { uniq }, through: :program_courses
end

If I create a course like this:

c = program.courses.create(name: 'Amazing Course')

The ProgramCourse record is created along with the new Course. However, if I do so like this:

c = program.courses.new(name: 'Amazing Course')
c.save

Only the Course is created. Is this a bug? Is there something syntactically off with my relationship? Can anyone explain why these two are different?

Pcushing
  • 361
  • 2
  • 7
  • 1
    Does it work if you use "build" instead of "new" on the second example? Sometime ago they used to be different methods, I'm not sure for ROR4 – AndreDurao Dec 31 '20 at 21:46
  • Does this answer your question? [using has\_many :through and build](https://stackoverflow.com/questions/9346261/using-has-many-through-and-build) – Eyeslandic Dec 31 '20 at 22:03

1 Answers1

-2
class ProgramCourse < ActiveRecord::Base
  belongs_to :course
  belongs_to :program
end

class Course < ActiveRecord::Base
  has_many :program_courses
  has_many :programs, -> { uniq }, through: :program_courses
end

class Program < ActiveRecord::Base
  has_many :program_courses
  has_many :courses, -> { uniq }, through: :program_courses
  accepts_nested_attributes_for :program_courses, :courses
end

You need to add this in the model to use this or you can use the build method to create the associated record

c = program.courses.build(name: 'Amazing Course')
c.save
OmG
  • 18,337
  • 10
  • 57
  • 90