需要另一个特定模型的多对多关系
我通过Supply – 和Origin -models在超市 , 产品和品牌之间建立了多对多的关系。 我还想在我的超市里存储我所拥有的特定产品品牌组合。 我想到了另一个模型(我称之为Specific_Combination
,我将存储:supermarket_id
, :product_id
和:brand_id
。
class Supermarket :supplies end class Supply < ActiveRecord::Base belongs_to :product belongs_to :supermarket end class Product :supplies has_many :origins has_many :brands, :through => :origins end class Origin < ActiveRecord::Base belongs_to :products belongs_to :brands end class Brand :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 :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
/编辑
在这里,我可能有供应属于原产地而不是产品。
另外,想想你是否需要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)
- 您将如何使用rails和ActiveRecord中的引用和引用对文章进行建模?
- 如何让Rails获得急切的负载计数?
- 跳过相关对象的validation – rails activerecord
- ProtocolViolation:ERROR:绑定消息提供0个参数,但是准备好的语句“”需要1
- Rails:调用“id”主键方法时出现“Stack level too deep”错误
- GroupingError:ERROR:列必须出现在GROUP BY子句中或用于聚合函数
- 是否有一个干净的API用于在ActiveRecord中的’reload’上重置实例变量?
- 将数组#select转换为rails 4中的活动记录查询
- Rails-y查询具有belongs_to关联的模型的方法