Many-to-Many-to-Many relationship with need for another specific model

前端 未结 1 417
遇见更好的自我
遇见更好的自我 2021-01-29 03:25

I have a many-to-many relationship between Supermarket, Product and Brand through the Supply- and Origin-mod

相关标签:
1条回答
  • 2021-01-29 04:05

    Here, I might have supply belong to origin instead of product.

    Also, think about whether you need SpecificCombination. What operations are you going to do with it? Are you going to list all the SpecificCombinations in your database? Are you going to search to find a specific one? Are you going to create a new combination?

    Then think if these operations can be done simply with the other classes?

    class Supermarket < ActiveRecord::Base
      has_many :supplies
      has_many :origins, :through => :supplies
    
      def self.choice
        Supermarket.all.map { |supermarket| [ supermarket.name, supermarket.id ] }
      end
    end
    
    end
    
    class Supply < ActiveRecord::Base  
      belongs_to :origin
      belongs_to :supermarket  
    end
    
    class Origin < ActiveRecord::Base
      belongs_to :supplies
      belongs_to :brands
    end
    
    
    walmart = Supermarket.create(:name => "Walmart");
    
    cornflakes = Product.create(:name => "Corn Flakes");
    kellogs = Brand.create(:name => "Kellog's");
    walmart.origins.create(:product_id => cornflakes, :brand_id = kellogs)
    
    0 讨论(0)
提交回复
热议问题