我有以下型号
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
当我尝试为某个选项创建新投票,然后尝试保存帖子时,它不会显示:
@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.... ¯\_(ツ)_/¯
似乎即使我正在保存poll
2 级以下的关联也没有被保存。
我也尝试过这样解决它:
@poll.votes.new(option: @poll.options.first)
@poll.save
但这给了我以下错误:
ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection:无法修改关联“Poll#votes”,因为源反射类“Vote”通过:has_many 关联到“Option”。来自 /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'