0

私はコードの初心者で、ユーザー モデルと製品モデルの 2 つの接続モデルをセットアップしようとしています。製品モデルには 2 人のユーザーがいて、1 人は所有者で、もう 1 人は借用者です。ユーザー モデルには、所有者および借用者として多くの製品があります。

以下のコードが私の目的を満たしているかどうか知っていますか?

class User
    has_many :products
end

class Product
    belongs_to :owner, class_name: "User", foreign_key: "user_id"
    has_one :borrower, class_name: "User", foreign_key: "user_id"
end
4

2 に答える 2

2

実際には、 User モデルを「指す」 Product モデルに 2 つの異なる列が必要です。

owner_id, borrower_id

User モデルは次のようになります。

class User
  has_many :owned_products, class_name: "Product", foreign_key: "owner_id"
  has_many :borrowed_products, class_name: "Product", foreign_key: "borrower_id"
end

そしてあなたの製品モデルは次のようになります:

class Product
    belongs_to :owner, class_name: "User", foreign_key: "owner_id"
    belongs_to :borrower, class_name: "User", foreign_key: "borrower_id"
end
于 2013-05-14T07:50:58.907 に答える
1

STI アプローチ (単一継承テーブル) を使用できます。

モデル ユーザー:

class User < ActiveRecord::Base
   # general attributes and validations and the like
end

所有者モデル:

class Owner < User
  # specific attributes and/or validations if any
  has_many :products
end

借り手モデル:

class Borrower < User
  # specific attributes and/or validations if any
  haas_many :products
end

製品モデル:

class Product < ActiveRecord::Base
  # attributes, validation and the like
  belongs_to :owner
  belongs_to :borrower
end

基本的に、所有者と借用者をユーザー型として編成し、その属性を継承します。

one_owner.productsone_owner が所有する製品が表示されます

one_borrower.productsone_borrower が借りた製品が表示されます

one_product.ownerその製品の所有者が表示されます

one_product.borrowerその製品の借り手が表示されます

次のスレッドで広範な例を見ることができます

于 2013-05-14T07:50:11.963 に答える