0

我正在尝试创建一个应用程序来分享或提供产品。所以我有两个模型:用户和产品。用户可以拥有许多产品,作为所有者或作为借款人。一个产品只有一个所有者和一个借款人。

首先我做了这样的事情

> rails generate model User name:string
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

> rails generate model Product name:string owner_id:integer borrower_id:integer
class Product
  belongs_to :owner, class_name: "User", foreign_key: "owner_id"
  belongs_to :borrower, class_name: "User", foreign_key: "borrower_id"
end

我在我的产品控制器中添加了一个安全过滤器,它只为产品所有者启用更新方法。但是当我想更改产品的借用人时,我遇到了一些问题,因为借用人从来都不是所有者,因此无法更新产品。

所以现在我想知道我是否应该将 foreign_key 从我的产品模型中取出,以便将用户对自己产品的更新操作与用户借用不属于的产品的更新操作分离给他...

> rails generate model User name:string
class User
  has_many :properties
  has_many :loans
  has_many :owned_products, through: :properties
  has_many :borrowed_products, through: :loans
end

> rails generate model Property owner_id:integer owned_product_id:integer
class Property
  belongs_to :owner, class_name: "User", foreign_key: "user_id"
  belongs_to :owned_product, class_name: "Product", foreign_key: "product_id"
end

> rails generate model Loan borrower_id:integer borrowed_product_id:integer
class Loan
  belongs_to :borrower, class_name: "User", foreign_key: "user_id"
  belongs_to :borrowed_product, class_name: "Product", foreign_key: "product_id"
end

> rails generate model Product name:string
class Product
  has_one :property
  has_one :loan
  has_one :owner, through: :property
  has_one :borrower, through: :loan
end

你怎么看待这件事 ?

4

1 回答 1

1

由于借来的产品和拥有的产品是具有相同属性列表的相同类型的对象,但仅在行为上有所不同,因此我会为Product.

迁移:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      # ...

      t.timestamps
    end
  end
end

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.integer :ownerable_id
      t.string :ownerable_type
      # ...

      t.timestamps
    end
  end
end

楷模:

class User < ActiveRecord::Base
  has_many :products, :as => :ownerable
end

class Product < ActiveRecord::Base
  belongs_to :user, :polymorphic => true
end

class OwnedProduct < Product
end

class BorrowedProduct < Product
end

这种方法的好处是您可以在每个模型中定义适当的行为,而无需询问它是“拥有”还是“借用”。只需告诉您的模型该做什么,然后将决策留给每个对象来做正确的事情。

于 2013-06-03T17:00:16.370 回答