我有以下担忧:
module Eventable
extend ActiveSupport::Concern
# ...
included do
has_many :subscriptions, as: :entity, dependent: :destroy
end
end
我的模型是:
class Experiment < ActiveRecord::Base
include Eventable
end
class Subscription < ActiveRecord::Base
belongs_to :entity, polymorphic: true
end
在我的控制器中,我尝试为实验创建订阅,如下所示:
class SubscriptionsController < ApplicationController
before_filter :find_entity
def create
subscription = Subscriptions.new(params[:subscription])
@entity.subscriptions << subscription # Why is it false?
# ...
end
end
但它不起作用。
在调试时,我注意到
@entity.subscriptions.count
创建了不正确的 SQL 查询:
SELECT COUNT(*) FROM [subscriptions] WHERE [subscriptions].[experiment_id] = 123
虽然我期望:
SELECT COUNT(*) FROM [subscriptions] WHERE [subscriptions].[entity_id] = 123 AND [subscriptions].[entity_type] = 'Experiment'
注意:如果我执行以下操作,它可以正常工作:
subscription.entity = @entity
subscription.save
感谢帮助!