0

我通过Supply - 和Origin - 模型在SupermarketProductBrand之间建立了多对多的关系。我还想存储我在超市中拥有的特定产品-品牌-组合。我想到了另一个模型(我把它叫做我要存储的地方,和.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。你打算用它做什么操作?您要列出数据库中的所有特定组合吗?您要搜索以找到特定的吗?你要创造一个新的组合吗?

然后想想这些操作是否可以简单地用其他类来完成?

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 回答