在我的模型中, Item
由User
创建,可由许多Users
购买,User
可以购买许多Items
。< / p>
使用User
定义了Item
,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 :(得分: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
模型将能够识别关联。