yazoou
yazoou

Reputation: 67

Rails 4 has_many through - Cannot modify association

I have DayItem model which has one SchoolProgram which has many seminars.

class DayItem < ActiveRecord::Base
  has_one :school_program, dependent: :destroy
  has_many :seminars, through: :school_program

  accepts_nested_attributes_for :school_program
  accepts_nested_attributes_for :seminars, reject_if: :all_blank
end

class SchoolProgram < ActiveRecord::Base
  belongs_to :day_item
  has_many :seminars, dependent: :destroy

  accepts_nested_attributes_for :seminars, allow_destroy: true, reject_if: :all_blank
end

class Seminar < ActiveRecord::Base
  belongs_to :school_program
end

I am using cocoon gem for dynamic nested forms as follows.

_form.html.haml:

= simple_form_for [@day, @day_item] do |f|
  = f.input :start_time
  = f.simple_fields_for :school_program do |form|
    = form.input :school
    = form.simple_fields_for :seminars do |seminar|
      = render 'seminar_fields', :f => seminar, :parent => form
    .links
      = link_to_add_association 'add seminar', form, :seminars

_seminar_fields.html.haml:

.nested-fields.well.well-compact
  .form-inline
    = f.input :name
    = link_to_remove_association "remove seminar", f

But when I try to add a seminar I get following exception.

 ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection in Etm::DayItemsController#update

Cannot modify association 'DayItem#seminars' because the source reflection class 'Seminar' is associated to 'SchoolProgram' via :has_many.

Any help is appreciated.

Upvotes: 0

Views: 1732

Answers (1)

Elvn
Elvn

Reputation: 3057

Circular reference in relationships (source reflection)

There may be more than one issue here, but the first one that should be addressed is that your relationship for Seminars creates a circular reference. It is declared in a has_many in DayItem and then as a has_one on SchoolProgram, which itself belongs to the parent class DayItem. Please try the change below to our DayItem model. Leave the other models as they are, and let me know how that goes.

class DayItem < ActiveRecord::Base
  has_one :school_program, dependent: :destroy

  accepts_nested_attributes_for :school_program
end

enter image description here

Upvotes: 1

Related Questions