これは不自然な例です。たとえば、ある人が友達を持っている国の人口をリストしたい場合、以下に2つの設定を示します。モデルでデータを繰り返すのが最善でしょうか?
デメテルの法則に従うことが重要だと言われました。例としては、犬に歩くように指示する場合、足に歩くように命令するのは愚かです。
People.where(:country => friend.country)
私の豊富な経験のなさ(noob)で、モデルがデータを繰り返す場合、 (これまで不可能だった)連鎖した関連付けがあるコレクションと比較して、クエリがはるかに簡単になることがわかりました:(People.where(:city => { :county => { :region => { :country => friend.city.county.region.country }}})
これは本当にこのnoobに役立ちますここで、正しい工夫されたLoDの設定と構文を想像できれば、概念を理解できます。デメテルの法則とは関係のない例を使用しなかったことを願っています)LoDを適用してみdelegate
たところ、まだ連鎖している(私はそうです)が、私が考えることができる唯一の解決策は、関連付けを介してアクセスできるデータを繰り返すことです。
しかし、私はデータを繰り返すのが嫌いです!これは、Twitterを再作成するDHHのRailsのチュートリアルをフォローしているためです。彼は、関係を作成することとデータを繰り返すことの素晴らしさを示しました。
アソシエーションの連鎖を少なくするには、データを繰り返すことが適切である必要がありますか?
モデル、繰り返しデータ
class Country < ActiveRecord::Base
has_many :regions
has_many :counties
has_many :cities
has_many :people
end
class Region < ActiveRecord::Base
has_one :country
has_many :counties
has_many :cities
has_many :people
end
class County < ActiveRecord::Base
has_one :country
has_one :region
has_many :cities
has_many :people
end
class City < ActiveRecord::Base
has_one :country
has_one :region
has_one :county
has_many :people
end
class Person < ActiveRecord::Base
has_one :country
has_one :region
has_one :county
has_one :city
has_many :relationships
has_many :friends, :through => :relationships
end
vs連鎖関連のあるモデル
class Country < ActiveRecord::Base
has_many :regions
end
class Region < ActiveRecord::Base
belongs_to :country
has_many :counties
end
class County < ActiveRecord::Base
belongs_to :region
has_many :cities
end
class City < ActiveRecord::Base
belongs_to :county
end
class Person < ActiveRecord::Base
belongs_to :city
end