0

我有以下担忧:

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

感谢帮助!

4

1 回答 1

0

此错误的原因:(class Experiment不是我的班级)已经有has_many :subscriptions

建议:如果您有奇怪的行为,并且您使用其他人的代码,请停止并查看代码!

于 2013-08-10T21:48:29.460 回答