ActiveRecord - Associations 2 level down are not being saved

59 views Asked by At

I have the following models

class Poll < ApplicationRecord
    has_many :options, dependent: :destroy
    has_many :votes, through: :options

    accepts_nested_attributes_for :options
end

class Option < ApplicationRecord
  belongs_to :poll
  has_many :votes, dependent: :destroy
end

class Vote < ApplicationRecord
  belongs_to :option
end

When I try to create a new vote for an option, and then try to save the post, it will not be shown:

@poll = Poll.first
@poll.options.first.votes.length # returns 3
@poll.options.first.votes.new
@poll.options.first.votes.length # returns 4
@poll.save # returns true
@poll.votes.length # returns 3.... ¯\_(ツ)_/¯ 

Seems like even though I am saving the poll, the associations 2 levels down are not being saved.

I have also tried to solve it like this:

@poll.votes.new(option: @poll.options.first)
@poll.save

But this gives me the following error:

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection: Cannot modify association 'Poll#votes' because the source reflection class 'Vote' is associated to 'Option' via :has_many. from /home/dbugger/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2.1/lib/active_record/associations/through_association.rb:94:in `ensure_mutable'

0

There are 0 answers