ActiveRecord :: EagerLoadPolymorphicError:无法急切加载多态关联:sender

时间:2014-10-25 21:31:33

标签: ruby-on-rails

我将此工作用于其他模型,但似乎无法使用Notifications表(使用用户模型)。

错误指向此行count_of_males = Notification.joins(:sender).where(users: {gender: 'male'}).uniq.count

我正在通知表sender_id中确定用户是男性还是女性(来自用户的表gender列)。

用户模型:

  def self.total_male
    count_of_males = Notification.joins(:sender).where(users: {gender: 'male'}).uniq.count
  end

  def self.total_female
    count_of_males = Notification.joins(:sender).where(users: {gender: 'female'}).uniq.count
  end

查看:

    <%= User.total_male %> Dates by Males
    <P>
    <%= User.total_female %> Dates by Females

1 个答案:

答案 0 :(得分:3)

您将无法在:sender上进行联接,因为它是您Mailboxer::Notificationhttps://github.com/mailboxer/mailboxer/blob/master/app/models/mailboxer/notification.rb#L7

的多态关联

您可以采用多种方法,其中一种方法是使用SQL片段进行连接,这样您就可以传递users表的附加条件。例如:

join_clause = "INNER JOIN users ON notifications.sender_id = users.id AND notifications.sender_type = 'User'"
Notification.joins(join_clause).where(users: { gender: 'female' }).uniq.count