15

I have the following models:

class Business < ActiveRecord::Base
  has_many :customers, :inverse_of => :business
  has_many :payments, :inverse_of => :business
end

class Customer < ActiveRecord::Base
  belongs_to :business, :inverse_of => :customer
  has_many :payments, :inverse_of => :customer 
end

class Payment < ActiveRecord::Base
  belongs_to :customer, :inverse_of => :payment 
  belongs_to :business, :inverse_of => :payment
end

Doing business.customers works fine. However, when I do business.payments I get an error: Could not find the inverse association for business (:payment in Business).

I'm not sure why though. I have the same exact associations both ways. My schema.db also looks fine. What could be the issue here?

EDIT When I remove the inverse_of => :business for has_many :payments, it works. Why does this happen? Is it related to that Payment belongs to customer and business (it shouldn't really matter, right?)?

4

2 回答 2

29

Update Payment model with this:

class Payment < ActiveRecord::Base
  belongs_to :customer, :inverse_of => :payments 
  belongs_to :business, :inverse_of => :payments
end

you declared

has_many :payments, :inverse_of => :business in Business model

but in Payment you used belongs_to :business, :inverse_of => :payment

it should be belongs_to :business, :inverse_of => :payments

于 2013-06-21T11:00:37.593 回答
0

Your problem is at:

belongs_to :business, :inverse_of => :customer

and at:

belongs_to :customer, :inverse_of => :payment 
belongs_to :business, :inverse_of => :payment

The other side of belongs_to is has_many, which defines a plural relation. That means the inverse_of should be customers instead of customer and payments instead of payment.

于 2013-06-21T11:00:36.997 回答