2013-05-17 22 views
1

在我的模型中ItemUser創建的,可由多個Users購買,並且User可以購買許多Items多對多的關係:通過給「無法找到該協會的錯誤

UserItem,和Purchase定義,使用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 

rspec測試也剪斷如下:

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.buyers.should include @user@user.purchased_items.should include @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 

migration看起來像

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 

我做了什麼錯?

+0

如果在User和Item中刪除'::source =>:item',會發生Wat? –

+0

好問題。我只是嘗試了這一點,而不是一個區別。我仍然得到'無法找到關聯:在模型項目中購買(反之亦然)。 –

回答

2

您必須指定以下內容。

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 

只有當你指定

 has_many :purchases 

該模型將能夠識別的關聯。

+0

太棒了;非常感謝。 –