Pankaj Singh
Pankaj Singh

Reputation: 41

Rails Reverse Polymorphic Association

I am building a fee module for one of the school. To make the fee module work, I want to define the fee templates (structure) which will have different types of fees (admission fee, library fee, sports fee etc), various discounts and any tax applicable. The fees, discounts and taxes are defined as different models as they contain different properties.

Here are the various models ...

First the fee templates

class FeeTemplate < ActiveRecord::Base
    has_many :fee_template_particulars
end

and then the FeeParticulars ..

class FeeParticular < ActiveRecord::Base
    belongs_to :fee_template
    belongs_to :particulars, :polymorphic => true
end

Now fee, discount and tax model

class Fee < ActiveRecord::Base
    has_many :fee_particulars, :as => particulars
end

class Discount < ActiveRecord::Base
    has_many :fee_particulars, :as => particulars
end

class Tax < ActiveRecord::Base
    has_many :fee_particulars, :as => particulars
end

Essentially, database table for FeeTemplateParticular will have a type column to store the type of fee/discount/tax and the id record.

Wanted to ask you guys few questions on the scenario I have to implement ..

  1. Is the approach (polymorohic) good for this situation?

  2. If above is okay and knowing the polymorphic association works one way but in my case, I will have to find the details of each type fee/discount/tax from the fee particulars and not the other way around. How would that be done?

  3. Is there any better way to solve this problem.

Thanks in advance.

Upvotes: 4

Views: 1096

Answers (1)

Marlin Pierce
Marlin Pierce

Reputation: 10089

Yes this is good.

You have the field_particular for the has_many to find the particulars of different types. You will be able to have different classes for the different behavior of the particulars. I think this is a very good design for your problem.

Upvotes: 1

Related Questions