Rails多态关系不会隐式传播

时间:2013-03-04 23:37:28

标签: ruby-on-rails ruby capybara rails-activerecord

我有以下两个班级

 class Car < Vehicle
   has_one :steering_wheel, as: :attached
 end

 class SteeringWheel < ActiveRecord::Base
   belongs_to :attached

   has_many :components
   has_one :rim, class_name: 'Components', order: 'id DESC'
   attr_accessible :components
 end

 class Component < ActiveRecord::Base
    include SpecificationFileService::Client

    attr_accessible :created_by
    belongs_to :steering_wheel 
 end

然后在我的规格中:

context "given an attachment", :js do
  before do
    @car = create(:car, make: "honda")
    @steering_wheel = SteeringWheel.create(attached: @car)
    @steering_wheel.save
    @car.save
    @car.reload
  end
  specify "test the setup", :js do
    puts @car.steering_wheel
  end
end

打印:nil

我找到的一种解决方法是在车上明确设置steering_wheel:

 @car.steering_wheel = @steering_wheel

就在save

之前

编辑:

正如下面的评论所示,我尝试添加多态:true,但没有解决问题。另外,我已经充实了更多上面的SteeringWheel模型

我的问题是为什么,以及如何隐式地将其添加到回调链

1 个答案:

答案 0 :(得分:1)

与评论中提到的@ abraham-p一样,您需要将belongs_to关系声明为:

belongs_to :attached, polymorphic: true

否则,它会尝试查找Attached模型,并确保在SteeringWheel模型中包含这些字段:

attached_type
attached_id

其余的由Rails制定:)