1

私は3つのモデルを持っています:

Article (:title)
  has_many :units
Dealer (:name, :adress)
  has_many :units
Unit (:price, :dealer_id, :article_id)
  belongs_to :article
  belongs_to :dealer

自分のテーブルが完全に正しいかどうかわかりません。また、 has_many :through を使用する必要があるのか​​、それとも has:many を使用して所属するだけなのかわかりません。違いは正確には何ですか?

そして、レールクエリはどのように見えるでしょうか?

Article.find(:name => "Cheese").units
Article.find(:name => "cheese").units.minimum('price').dealer 

このような複雑な Rails クエリは、この種の関係で機能しますか?

4

1 に答える 1

2

次のように has_many を宣言できます。

Unit (:price, :dealer_id, :article_id)
  belongs_to :article
  belongs_to :dealer

Article (:title)
  has_many :units
  has_many :dealers, through: :units

Dealer (:name, :adress)
  has_many :units
  has_many :articles, through: :units

を使用するhas_many :objects, through: :relationと、特定のエントリのオブジェクトにアクセスできます。

@dealer.articles
# and
@article.dealers

これhas_many through:は別の方法ですhas_and_belongs_to_many: 結合モデルに追加の属性と検証を許可します( Ruby スタイル ガイド)

以下を実行すると、DB に対して 2 つのクエリが生成されます。

Article.find(:name => "Cheese").units

Unit モデルには属性があることがわかっていますarticle_id。この場合の最良の方法は次のとおりです (記事の ID を知っていると仮定して):

Unit.where(article_id: article.id)

これにより、DB へのクエリが 1 つだけ生成されます。

于 2013-01-03T20:13:50.117 に答える