2017-08-21 76 views
1

我不確定處理這種情況的最佳方法,並且會欣賞某些方向。基本上,我有一個場景,我需要爲組織記錄資產。Polymorphic,STI或其他

有多種類型的資產,因此屬性的類型不同而不同類型但有共同的一些領域的所有資產,如:

location 
make 
model 
colour 
purchase_date 
warranty_period 

類似: How to design a product table for many kinds of product where each product has many parameters

我通過創建此作爲

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],並呈現與資產類型相關的部分對應表單。

這是走下正確的道路還是有更好的方法來實現這一目標?它確實感覺很笨重。

回答

0

我認爲使用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組織形式。資產模型將包含組織和每個單一細節模型之間的引用,但如果您在視圖或特殊字段中更多地使用它,則所有內容都將被分離。