0

私はUser modelとを持っていproduct modelます。

User has_many :products, :dependent => :destroy
Product belongs_to :user, :foreign_key => "user_id", touch: true

すべてのユーザーのウィッシュリストを作成したい。したがってwishlist model、適切な関連付けを作成する必要があります。しかし、私は開始する方法がわかりません。ウィッシュリスト モデルにはid, user_idandproduct_idフィールドが含まれていると思います

has_many through associationまたはを使用する必要がありhas_and_belongs_to_many ますか? また、ユーザーがウィッシュリストを破棄するために破棄された場合も必要です。

最善の方法は何ですか?どうもありがとう!

4

3 に答える 3

1

@ JZ11 が指摘したように、製品をユーザーに直接リンクするべきではありません (ユーザーが実際に何らかの理由で製品を「所有」している場合を除きます)。ただし、Wishlist アイテムを構成するモデルが見落とされていました。

class User < ActiveRecord::Base
  has_many :wishlists       # or has_one, depending on how many lists a User can have...
end

class Product < ActiveRecord::Base
  has_many :wishlist_items
end

class Wishlist < ActiveRecord::Base
  belongs_to :user
  has_many :wishlist_items
  has_many :products, :through => :wishlist_items
end

class WishlistItem < ActiveRecord::Base
  belongs_to :product
  belongs_to :wishlist
end

当然、必要に応じて追加:dependent => :destroyする必要があります。

于 2013-10-14T20:18:10.963 に答える
0

結合テーブルを作成するには、次のようにします。

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 の回答は確認しませんでしたが、それがその方法である可能性があります)。

于 2013-10-14T20:37:52.250 に答える