多态性、性传播感染或其他



我不确定处理这种情况的最佳方法,并希望得到一些指导。从本质上讲,我有一个场景,我需要为组织记录资产。

有各种类型的资产,因此属性因类型而异,但是所有资产都有许多共同的字段,例如:

location
make
model
colour
purchase_date
warranty_period

似: 如何为每种产品设计产品表,其中每个产品具有许多参数

我通过创建它作为

one-to_many between Organisation and Asset
polymorhpic between Asset and Details
class Organisation < ApplicationRecord
has_many :assets
end
class Asset < ApplicationRecord
belongs_to :organisation
belongs to :detail, polymorphic: true
end
class CarAsset < ApplicationRecord
has_one :asset, as: :detail
end
class ComputerAsset < ApplicationRecord
has_one :asset, as: :detail
end

我的问题是:我希望在单个表单操作中创建资产和详细信息,以便用户在选择资产类型后为两个模型创建单个表单条目。

用户将单击组织显示页面上的链接:

<%= link_to "New car asset", new_organisation_asset_path(@organisation, query: :new_car_asset) %>

在我的控制器中,我可以做类似的事情:

class AssetsController < ApplicationController
def new
@organisation = Organisation.find(params["organisation_id"])
@asset  = @organisation.assets.new
case params[:query]
when "new_car_asset"
@details = @asset.car_assets.new
when "new_computer_asset"
@details = @asset.computer_assets.new
end
end
end

在我看来,我还可以检查 params[:query] 的值,并渲染与资产类型相关的相应表单部分。

这是正确的道路,还是有更好的方法来实现这一目标?确实感觉很笨重。

我认为使用has_many :trough可能会更好,从长远来看应该会从中获得更多。喜欢这个:

class Organisation < ApplicationRecord
has_many :cars, through: assets
has_many :cumputers, through: assets
has_many :locations, through: assets
has_many :purchase_date, through: assets
end
class Asset < ApplicationRecord
belongs_to :organisation
belongs_to :cars
belongs_to :cumputers
belongs_to any :locations
belongs_to :purchase_date
end
class Car < ApplicationRecord
has_one :organisation, through: assets
end
class Cumputer < ApplicationRecord
has_one :organisation, through: assets
end
class Location < ApplicationRecord
has_one :organisation, through: assets
end
class Purchase_date < ApplicationRecord
has_one :organisation, through: assets
end

然后,您可以在Organisations_controller中创建资产,并可以使用fields_for嵌套组织表单中的所有内容。资产模型将包含组织与每个细节模型之间的引用,但如果您想在视图或特殊字段中使用它做更多的事情,那么一切都将是分开的。

最新更新