2012-03-05 20 views
0

私のデータベースの基本構造を設定するのは難しいです。Railsの1対多の関係

私には製品(約50)があります。各製品は以上個の場所に関連しています。

基本的なスキーマは、この(まだありませ関係)

製品

id:integer 
name:string 

場所

id:integer 
name:string 
content:string 

だろう私が最初に私が製品にplace_idを追加することにより、場所や製品を接続することができ取り払わとコントローラにはhas_manybelong_toがありますが、製品には複数の場所がある可能性があるため、どのようにしたらよいか分かりません。

答えて

1

商品にhas_many場所と場所has_many製品がある場合、あなたの協会は多対多である必要があります。

これを行うには2通りの方法がありますが、最も推奨されるのが結合モデルです。あなたは明示的に商品と場所の関係にラベルを付けます。あなたはそれが次のようになり、ProductLocationやショップまたは同様にそれを呼び出すことができます。

product_locations: 
    product_id 
    place_id 

class ProductLocation < ActiveRecord::Base 
    belongs_to :product 
    belongs_to :place 
end 

class Place < ActiveRecord::Base 
    has_many :product_locations 
    has_many :products, :through => :product_locations 
end 

class Product < ActiveRecord::Base 
    has_many :product_locations 
    has_many :places, :through => :product_locations 
end 

は、製品や場所との間の関係が簡単であるため、私は、余分な情報の必要性を `habtm`を使用していないだろうhttp://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many

0

product_idplacesを追加したいと思うようです。製品

1

belongs_toの

製品にhas_manyの場所

場所は、ちょうど接続を介して

ProductsPlaces(新しいテーブル)

product_id 
place_id 

とモデル

class Product < ActiveRecord::Base 
    has_many :places, :through => :products_places 
end 

class Place < ActiveRecord::Base 
    has_many :products, :through => :products_places 
end 
での使用します

はまた、実際には(ProductsPlacesテーブル付き)同じことを行うhas_and_belongs_to_manyアソシエーション

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :places 
end 

class Place < ActiveRecord::Base 
    has_and_belongs_to_many :products 
end 

しかし、より良いhas_and_belongs_to_manyアソシエーションが廃止されますので、通じ使用があります。

+1

を参照してください。 。また、私はチェックして、非難されることはありません: "廃止されました:has_and_belongs_to_many アソシエーションの追加属性を使用する代わりに、あなたのアソシエーションを実際の結合モデルにアップグレードする [DHH]"(http://www.ruby-forum.com/topic/139047)。関数自体は廃止されません。 –

+0

hmご意見ありがとうございます。私の最後のチームリーダーが、廃止予定のためにhas_and_belongs_to_manyを使用しないと言ったので、本当に面白いです。 – Ximik

+0

さらに、私はレールガイドをチェックしました: 'has_and_belongs_to_many関連での結合テーブルの余分な属性の使用は廃止されました。 2対多の関係で2つのモデルを結合するテーブルでこの種の複雑な動作が必要な場合は、has_and_belongs_to_many.http://guides.rubyonrailsの代わりにhas_many:throughの関連付けを使用する必要があります。org/association_basics.html) –