I am unsure of the best way to approach this scenario and would appreciate some direction. Essentially I have a scenario whereby I need to record assets for an organisation.
There are various types of assets so the attributes differ from type to type however there are a number of fields common to all assets such as:
location
make
model
colour
purchase_date
warranty_period
Similar to: How to design a product table for many kinds of product where each product has many parameters
I had through of creating this as
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
My question is: I wish to create the asset & detail in a single form action so the user after selecting the asset type makes a single form entry for both models.
The user would click a link on the organisation show page:
<%= link_to "New car asset", new_organisation_asset_path(@organisation, query: :new_car_asset) %>
The in my controller I could do something similar to:
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
In my view I could also check the value of params[:query] and render the corresponding form partial that relates to the asset type.
Is this going down the correct path or is there a better way to achieve this? It does feel quite clunky.