【发布时间】:2016-04-30 06:18:33
【问题描述】:
在 Rails 4.2 应用程序中,我有一个继承自 Draftsman 的模型。
module ActsAs
class Draft < Draftsman::Draft
include ActsAs::Votable
end
end
用户可以投票批准/拒绝编辑,ActsAs::Votable mixin 添加了这种多态关联和方法。
module ActsAs
module Votable
extend ActiveSupport::Concern
included do
has_many :votes_for,
class_name: 'ActsAs::Vote',
as: :votable,
dependent: :destroy
end
end
end
这适用于大多数父模型,但我在使用这个继承的 Draftsman 类时遇到了问题。
我可以创建投票
ActsAs::Vote.last
=> #<ActsAs::Vote id: 10, votable_id: 6, votable_type: "Draftsman::Draft">
但我无法退回草稿的选票
@draft = ActsAs::Draft.find(6)
@draft.votes_for
=> #<ActiveRecord::Associations::CollectionProxy []>
我尝试修改投票创建方法以将 votable_type 设置为 ActsAs::Draft 而不是继承的 Draftsman::Draft,但同样的问题仍然存在。
ActsAs::Vote.last
=> #<ActsAs::Vote id: 10, votable_id: 6, votable_type: "ActsAs::Draft">
@draft = ActsAs::Draft.find(6)
@draft.votes_for
=> #<ActiveRecord::Associations::CollectionProxy []>
Draftsmans::Draft 上显然没有定义关系
@draft = Draftsman::Draft.find(6)
@draft.votes_for
NoMethodError: undefined method `votes_for' for #<Draftsman::Draft:0x007fd7e6de9660>
当ActsAs::Vote.all显示表中存在记录时,为什么我无法通过@draft获取子投票?
【问题讨论】:
标签: ruby-on-rails inheritance sti