1

私のモデルでは、Itemは によって作成され、User多くの で購入でき、 は で多くUsersUserを購入でき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

私は何を間違えましたか?

4

1 に答える 1

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

モデルは関連付けを識別できるようになります。

于 2013-05-17T02:56:13.493 に答える