結合テーブルを作成するには、次のようにします。
rails g migration create_products_users_table
それが完了したら、以下のコードを追加して、結合テーブルにフィールドを作成する必要があります。結合テーブルに ID は必要ない:id => false
ため、 に注意してください。
class CreateProductsUsersTable < ActiveRecord::Migration
def change
create_table :products_users, :id => false do |t|
t.references :product
t.references :user
end
add_index :products_users, [:product_id, :user_id]
add_index :products_users, :user_id
end
end
上記のコードは、いくつかのインデックスも作成し、データベース レベルでも重複がないことを保証します。
モデルは次のようになります。
class Product < ActiveRecord::Base
has_and_belongs_to_many :users
end
class User < ActiveRecord::Base
has_and_belongs_to_many :products
end
ユーザーを削除するだけでなく、適切に破棄user.destroy
すると (違いがあります)、結合テーブル内の関連する行も削除されます。これは ActiveRecord に組み込まれています。
ただし、これを行っても実際には結合テーブルを使用できないことに注意してください。etc のようなコードやその他のグッズは受け付けますuser.products = [product1, product2]
が、ウィッシュ リストを実際に使用することはできません。
ウィッシュリストを使用したい場合は、中間の結合テーブルを別の方法で作成して使用する必要がありますhas_many :through
(PinyM の回答は確認しませんでしたが、それがその方法である可能性があります)。