【问题标题】:ActiveRecord polymorphic has_many with ActiveSupport::ConcernActiveRecord 多态 has_many 和 ActiveSupport::Concern
【发布时间】:2013-08-10 09:45:11
【问题描述】:

我有以下顾虑:

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

感谢您的帮助!

【问题讨论】:

  • 指示多态关联的 sql 查询失败,但 subscription.entity = @entity 有效,这对我来说似乎是一个冲突的结果。 是否有可能在创建新订阅时缺少一些重要属性,这使得@entity.subscriptions &lt;&lt; subsciption failed?

标签: sql ruby-on-rails activerecord ruby-on-rails-3.2 polymorphic-associations


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-26
    • 2012-09-14
    • 2015-12-29
    • 1970-01-01
    • 2010-12-13
    • 2013-02-01
    • 2014-07-04
    • 1970-01-01
    相关资源
    最近更新 更多