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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.