Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

Rails - Polymorphic association join table


I am currently trying to set up a model structure that seems quite simple, but I haven't quite got it down.

I have a model payment that can belong to either a customer or a supplier (which can both have many payments).

My question is simply whether I need to manually create an interface table to allow this, or if declaring the polymorphic associations will do this for me?

e.g. I have:

class Payment < ActiveRecord::Base
    belongs_to :payment_originator, :polymorphic => true
end

class Customer < ActiveRecord::Base
    has_many :payments, :as => :payment_originator
end

class Supplier < ActiveRecord::Base
    has_many :payments, :as => :payment_originator
end

Is this enough, or do I also need to use a generator to manually create the payment_originator model?

Thanks!


Solution

  • As far as the models go, this is good enough. You just need to migrate a :payment_originator_type and :payment_originator_id to the payments table. The associations you defined above will automatically fill these in for you.