Could Not Find Inverse Association for has_many in Rails 3

darksky picture darksky · Jun 21, 2013 · Viewed 9.8k times · Source

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?)?

Answer

Muntasim picture Muntasim · Jun 21, 2013

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