We are using a single table to store similar structure and data objects and link them together via self has_many relations. The table is called organizations, and we store Organizations, Comitents and Customers, following these rails 5 activerecord relations:
- a Organization has many Comitents
- a Comitent has many Customers
- Customers have an additional attribute last_doc stored in the join table organization_customers
All three objects are Organization objects, as you can see below:
class Organization < ApplicationRecord
has_many :customers, through: :organization_customers
has_many :comitents, through: :organization_comitents
class OrganizationCustomer < ApplicationRecord
belongs_to :customer, class_name: 'Organization'
class OrganizationComitent < ApplicationRecord
belongs_to :comitent, class_name: 'Organization'
We need to achieve the following goals:
# get an organization (SUCCESS)
o = Organization.first
=> #<Organization id: 1, name: "ACME", cuit: "99999999999", iibb: nil, accounting_firm: false, iibb_condition_id: nil, afip_condition_id: nil, mt_category_id: nil, created_at: "2017-06-25 22:51:45", updated_at: "2017-06-25 22:51:45", accounting_plan_id: nil>
# Get a comitent belong to that organization (SUCCESS)
=> #<Organization id: 3, name: "Pablo Orkit", cuit: "1234567890", iibb: "091090190", accounting_firm: false, iibb_condition_id: 1, afip_condition_id: 1, mt_category_id: 1, created_at: "2017-06-28 20:19:34", updated_at: "2017-08-02 13:06:56", accounting_plan_id: 2>
# Get a customer of the comitent of that organization (SUCCESS)
=> #<Organization id: 4, name: "Matrix", cuit: "1234567891", iibb: "", accounting_firm: false, iibb_condition_id: 1, afip_condition_id: 2, mt_category_id: 1, created_at: "2017-07-19 20:26:36", updated_at: "2017-07-19 20:26:36", accounting_plan_id: nil>
# get an attribute on join table for a customer (organization_customers) (FAILS)
=> NoMethodError: undefined method `last_doc' for #<Organization:0x00000004cfe140>
# save an attribute on join table for a customer (organization_customers) (FAILS)
a_customer = o.comitents.first.customers.first
a_customer.last_doc = "999"
=> NoMethodError: undefined method `last_doc=' for #<Organization:0x00000004c53c90>
As you can see, the we can't achieve the last two goals, related to an additional attribute for the Customer model stored in the organization_customers table used for the has_many relationship. We tried several possible solutions doing polymorphic models and accepts_nested_attributes_for :organization_customers method but without success.
We have been stuck with this problem for a couple of weeks and we need help to understand and solve the problem. Thank you.