Rails 3 个 HABTM 产生 ActiveRecord::Associations::CollectionProxy 个对象

Rails 3 HABTM yields ActiveRecord::Associations::CollectionProxy objects

我有一个遗留的 Rails 3 应用程序,我正在尝试在两个模型之间建立一个简单的 HABTM 关系:VolunteerCircle 和 User。我在其他两个模型中也有同样的关联。

协会如下:

志愿者圈模型:

class VolunteerCircle < ActiveRecord::Base 
    #...

    has_and_belongs_to_many   :users 

    # ...
end

用户模型:

class User < ActiveRecord::Base
  #...

  has_and_belongs_to_many :volunteer_circles

  #...
end

这里是迁移:

class CreateVolunteerCirclesUsers < ActiveRecord::Migration
  def change
    create_table :volunteer_circles_users, id: false do |t|
      t.belongs_to :volunteer_circle, index: true
      t.belongs_to :user, index: true
    end
  end
end

当我在 VolunteerCircle 对象上调用#users(或反之亦然)时,Rails 吐出一个 ActiveRecord::Associations::CollectionProxy 对象。

volunteer_circles_users table 在数据库中对我来说是正确的。我在这里错过了什么?

另外,我知道 HABTMT 的优越性。我无法控制的情况在这里决定了 HABTM。

非常感谢!

很难在这里找到错误..但也许其中一些会对您有所帮助:

我认为您缺少多字段索引:

add_index : volunteer_circles_users, [:volunteer_circles_id, :user_id]
add_index : volunteer_circles_users, [:user_id, :volunteer_circles_id]

而 create_join_table 按字母顺序创建它,因此它会是 user_volunteer_circles。因此,也许您可​​能需要执行以下操作:

class VolunteerCircle < ActiveRecord::Base 
    has_and_belongs_to_many :users, :join_table => : volunteer_circles_users
end

希望对您有所帮助..