Could Not Find Inverse Association for has_many in Rails 3

10,605

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

Share:
10,605
darksky
Author by

darksky

C, C++, Linux, x86, Python Low latency systems Also: iOS (Objective-C, Cocoa Touch), Ruby, Ruby on Rails, Django, Flask, JavaScript, Java, Bash.

Updated on June 13, 2022

Comments

  • darksky
    darksky almost 2 years

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

  • Anwar
    Anwar over 8 years
    The main point is that you must use proper pluralization for inverse_of: arguments. If it is inverse of many payments, use :payments, not :payment. Similar for business