Ruby on rails Rails:我应该总是定义模型之间的关联吗?

Ruby on rails Rails:我应该总是定义模型之间的关联吗?,ruby-on-rails,associations,ruby-on-rails-3,Ruby On Rails,Associations,Ruby On Rails 3,我有以下型号: class Aircon < ActiveRecord::Base belongs_to :shop belongs_to :brand belongs_to :power accepts_nested_attributes_for :shop, :brand, :power end class Shop < ActiveRecord::Base has_many :aircons has_many :brands, :through =&g

我有以下型号:

class Aircon < ActiveRecord::Base
  belongs_to :shop
  belongs_to :brand
  belongs_to :power
  accepts_nested_attributes_for :shop, :brand, :power
end

class Shop < ActiveRecord::Base
  has_many :aircons
  has_many :brands, :through => :aircons
  has_many :powers, :through => :aircons
end

class Brand < ActiveRecord::Base
  has_many :aircons
  has_many :shops,  :through => :aircons
  has_many :powers, :through => :aircons
end

class Power < ActiveRecord::Base
  has_many :aircons
  has_many :shops,  :through => :aircons
  has_many :brands, :through => :aircons
end
型号
空调
之间的适当关联是什么

问题3

您是否可以定义以下各项之间的关联:

  • 型号
    商店
  • 型号
    电源

如果是,什么类型的关联?

我记得模型可能是保留的。你可能得用Make

Q1 在Rails中双向链接模型是一种最佳实践

问题2 型号:has_many=>:aircons

空调:属于=>:型号

第三季度 我没有权力当模特。实际上,这是空调的一个特点。我猜空调的功率是BTUs或瓦特。所有飞行员都有的东西


然后你会说Aircons.find_by_power(500..1000)来查找所有功率为500到1000的Aircons,这不是我的意思。当然,如果你定义了A与B的关联,你应该定义B与A的关联。我的意思是,如果你有A、B、C和D模型,你应该定义它们之间的关联吗?Q2谢谢,这是有道理的。除非这真的是最自然的表达。没有什么事情自然会如此复杂。我可能会考虑重构我的责任。有时我们会被分割冲昏头脑,实际上会做更多的工作。问题3:我不明白将电源作为一个模型有什么不对,电源与商店/品牌有什么不同(除了它是一个数字而不是一个字符串)。如果不是这样的话,你怎么会发现,例如,所有功率=6kw的
Model
s?Aircon.find_by_power(6000)。map{i | i.Model}。uniq可以说效率较低,但并不困难。OK。
Power
Model
之间的关联如何?我认为电源有很多:型号,:至=>:aircons,但我不确定另一个方向(因为每个型号都属于特定的电源)。
class Model < ActiveRecord::Base
  belongs_to :brand
end  

class Brand < ActiveRecord::Base
  ...
  has_many :models
end