Rails 3 HABTM生成ActiveRecord :: Associations :: CollectionProxy对象

时间:2016-12-16 22:42:30

标签: ruby-on-rails ruby ruby-on-rails-3 activerecord associations

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

协会如下:

VolunteerCircle模型:

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表对我来说是正确的。我在这里缺少什么?

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

非常感谢你!

1 个答案:

答案 0 :(得分:0)

很难在这里找到错误..但也许其中一些可以帮到你:

我认为你错过了多字段索引:

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

希望有所帮助......