0

SupplyモデルとOriginモデルを通じて、SupermarketProduct、およびBrandの間に多対多の関係があります。また、スーパーマーケットにある特定の製品とブランドの組み合わせを保存したいと考えています。私は別のモデルを考えました (私はそれを私が保存する場所と呼びました,そして.Specific_Combination:supermarket_id:product_id:brand_id

class Supermarket < ActiveRecord::Base
  has_many :supplies
  has_many :products, :through => :supplies
end

class Supply < ActiveRecord::Base  
  belongs_to :product  
  belongs_to :supermarket  
end

class Product < ActiveRecord::Base
  has_many :supplies
  has_many :supermarkets, :through => :supplies

  has_many :origins
  has_many :brands, :through => :origins
end

class Origin < ActiveRecord::Base
  belongs_to :products
  belongs_to :brands
end

class Brand < ActiveRecord::Base
  has_many :origins
  has_many :products, :through => :origins
end

そして今、特定の製品とブランドの組み合わせを保存するために使用できると思ったクラス

class Specific_Combination < ActiveRecord::Base
  # to show which columns I would use:
  attr_accessible :supermarket_id, :product_id, :brand_id
end
  • これは適切なアプローチですか?
  • との間の関係をどのようにモデル化する必要がありSpecific_Combinationますか?
  • のアイテムにアクセス (作成...) するにはどうすればよいSpecific_Combinationですか?
  • より良いアプローチ (正規化) はどのようになりますか?

編集

class Supply < ActiveRecord::Base  
  belongs_to :origin  
  belongs_to :supermarket  
end

class Product < ActiveRecord::Base
  has_many :origins
end

class Origin < ActiveRecord::Base
  belongs_to :product
  belongs_to :brands
end

class Brand < ActiveRecord::Base
  has_many :origins
end

class Supermarket < ActiveRecord::Base
  has_many :supplies
  has_many :origins, :through => :supplies

  # my attempt to create an array of names of supermarkets
    def self.to_be_chosen
      chosen_supermarket = Array.new
      Supermarket.find_each do |supermarket|
        chosen_supermarket << supermarket.name
      end
    return chosen_supermarket
    end
end

/編集

4

1 に答える 1

0

ここでは、製品の代わりに原産地に属している供給があるかもしれません。

また、SpecificCombination が必要かどうかも考えてください。あなたはそれでどのような操作をするつもりですか?データベース内のすべての SpecificCombinations を一覧表示しますか? 特定のものを見つけるために検索しますか? 新たなコンビネーションを生み出しませんか?

次に、これらの操作を他のクラスで簡単に実行できるかどうかを考えてみてください。

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)
于 2012-09-16T12:58:05.347 に答える