Ruby 多对多关系:通过给予';找不到关联';错误

Ruby 多对多关系:通过给予';找不到关联';错误,ruby,activerecord,has-many-through,Ruby,Activerecord,Has Many Through,在我的模型中,项目由用户创建,可以由许多用户购买,而用户可以购买许多项目 用户、项目和购买使用AcvtiveRecord进行定义,为简洁起见,删除了多余的细节,如下所示: class User < ActiveRecord::Base # various other fields has_many :items, :foreign_key => :creator_id has_many :purchased_items, :through => :purchases

在我的模型中,
项目
用户
创建,可以由许多
用户
购买,而
用户
可以购买许多
项目

用户
项目
购买
使用
AcvtiveRecord
进行定义,为简洁起见,删除了多余的细节,如下所示:

class User < ActiveRecord::Base
  # various other fields
  has_many :items, :foreign_key => :creator_id
  has_many :purchased_items, :through => :purchases, :source => :item
end

class Item < ActiveRecord::Base
  # various other fields
  belongs_to :creator, :class_name => 'User'
  has_many :buyers, :through => :purchases, :source => :user
 end

 class Purchase < ActiveRecord::Base
   belongs_to :item
   belongs_to :user
  # various other fields
 end
describe "user purchasing" do
  it "should allow a user to purchase an item" do
    a_purchase = Purchase.create!(:item => @item, # set up in `before :each`
                                  :user => @user  # set up in `before :each`
    )
    a_purchase.should_not eq(nil)                 # passes
    @item.buyers.should include @user             # fails
    @user.purchased_items.should include @item    # fails
  end
end
这导致

1) Purchase user purchasing should allow a user to purchase an item
   Failure/Error: @item.buyers.should include @user
   ActiveRecord::HasManyThroughAssociationNotFoundError:
     Could not find the association :purchases in model Item
同样,如果我交换
@file_item.bullers.应该包括@user
@user.purchased_items.应该包括@item
,我会得到等价物

1) Purchase user purchasing should allow a user to purchase an item
   Failure/Error: @user.purchased_items.should include @item
   ActiveRecord::HasManyThroughAssociationNotFoundError:
     Could not find the association :purchases in model User
我的
迁移
看起来像

create_table :users do |t|
  # various fields
end

create_table :items do |t|
  t.integer :creator_id   # file belongs_to creator, user has_many items
  # various fields
end

create_table :purchases do |t|
  t.integer :user_id
  t.integer :item_id
  # various fields
end

我做错了什么?

您必须指定以下内容

class User < ActiveRecord::Base
  has_many :purchases
  has_many :items, :foreign_key => :creator_id
  has_many :purchased_items, :through => :purchases, :source => :item
end

class Item < ActiveRecord::Base
  # various other fields
  has_many :purchases
  belongs_to :creator, :class_name => 'User'
  has_many :buyers, :through => :purchases, :source => :user
end

该模型将能够识别关联。

如果在用户和项目中删除
,:source=>:item
,则会发生什么?好问题。我只是试了一下,没什么不同。我仍然得到
找不到关联:在模型项中购买
(反之亦然)。
      has_many :purchases