【问题标题】:Many to Many relationship :through giving 'Could not find the association' error多对多关系:通过给出“找不到关联”错误
【发布时间】:2013-05-17 02:14:21
【问题描述】:

在我的模型中,Item 是由 User 创建的,可以被许多 Users 购买,User 可以购买许多 Items

UserItemPurchase 是使用 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

我做错了什么?

【问题讨论】:

  • 如果你在 User 和 Item 中删除 , :source =&gt; :item 会发生什么?
  • 好问题。我只是尝试过,这并没有什么不同。我仍然得到Could not find the association :purchases in model Item(反之亦然)。

标签: ruby activerecord has-many-through


【解决方案1】:

您必须指定以下内容。

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-09-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    相关资源
    最近更新 更多