Custom db entry for 3 way habtm in ROR

后端 未结 1 1073
小蘑菇
小蘑菇 2021-01-06 18:00

I am converting an existing perl gtk app into a ROR app

I have a 3 way habtm association model.

class CustomerMaster < ActiveRecord::Base
  has_an         


        
相关标签:
1条回答
  • 2021-01-06 18:35

    Assume you are using Rails 3.

    You should use habtm when your join table has only 2 foreign keys. For most cases, has_many :through will be more flexible.

    In your case, you should create a model for the join table. First, you should disable pluralization for legacy DB schema. (I thought you already did that).

    # In config/application.rb
    config.active_record.pluralize_table_names = false
    

    Create a join table, namely CustomerPhoneAddress by convention (I will give it a more meaningful name):

    # customer_phone_address.rb
    class CustomerPhoneAddress < ActiveRecord::Base
      belongs_to :address_master
      belongs_to :customer_master
      belongs_to :phone_master
    end
    

    Finally, associate your models with has_many and has_many :through:

    # address_master.rb
    class AddressMaster < ActiveRecord::Base
      has_many :customer_phone_addresses
      has_many :customer_masters, :through => :customer_phone_addresses
      has_many :phone_masters, :through => :customer_phone_addresses
    end
    
    # customer_master.rb
    class CustomerMaster < ActiveRecord::Base
      has_many :customer_phone_addresses
      has_many :address_masters, :through => :customer_phone_addresses
      has_many :phone_masters, :through => :customer_phone_addresses
    end
    
    # phone_master.rb
    class PhoneMaster < ActiveRecord::Base
      has_many :customer_phone_addresses
      has_many :customer_masters, :through => :customer_phone_addresses
      has_many :phone_masters, :through => :customer_phone_addresses
    end
    

    I tested the code and it works very well. To create an association:

    CustomerPhoneAddress.create(
      :phone_master => PhoneMaster.first,
      :address_master => AddressMaster.first,
      :customer_master => CustomerMaster.first)
    

    To query the association:

    IRB> a = AddressMaster.first
    => #<AddressMaster id: 1, created_at: "2011-12-07 15:23:07", updated_at: "2011-12-07 15:23:07">
    IRB> a.customer_masters
    => [#<CustomerMaster id: 1, created_at: "2011-12-07 15:23:15", updated_at: "2011-12-07 15:23:15">]
    IRB> a.phone_masters
    => [#<PhoneMaster id: 1, created_at: "2011-12-07 15:23:19", updated_at: "2011-12-07 15:23:19">]
    IRB> a.customer_phone_addresses
    => [#<CustomerPhoneAddress id: 1, address_master_id: 1, customer_master_id: 1, phone_master_id: 1, created_at: "2011-12-07 15:24:01", updated_at: "2011-12-07 15:24:01">]
    
    0 讨论(0)
提交回复
热议问题