ActiveRecord-关联2级别未保存

时间:2019-05-17 16:37:21

标签: ruby-on-rails ruby activerecord ruby-on-rails-5.2 ruby-2.1.5

我有以下型号

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'< / p>

0 个答案:

没有答案