Rails4:ActiveRecord ... CollectionProxy:NoMethodError

时间:2014-01-21 15:39:24

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

我在rails4中遇到一些奇怪的错误,导致我无法在has_many关联上链接“收集”。

我有self has_many > folders
然后folder has_many > share_links
share_link has_many > devices

这可以按预期工作:

self.folders.first.share_links.first.devices

这不起作用:

self.folders
  .collect { |folder| folder.share_links }
  .collect { |share_link| share_link.devices }
  .uniq.count

有错误:

#<NoMethodError: undefined method `devices' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_ShaShareLink:0x007ff3b5f0dbf0>>

似乎收集不起作用,我觉得它确实有效?!

1 个答案:

答案 0 :(得分:4)

folder.share_links返回一个数组。所以self.folders.collect { |folder| folder.share_links }的结果是一个二维数组。您必须使用flatten

将其转换为单维数组
self.folders
  .collect { |folder| folder.share_links }.flatten
  .collect { |share_link| share_link.devices }.flatten
  .uniq.count

SQL

 Model
  .joins(:folders)
  .joins("share_links on share_links.folder_id = folders.id")
  .joins("devices on devices.share_links_id = share_links.id")
  .count("distinct('<id>')")