ruby on rails - Polymorphic, STI or other -
i unsure of best way approach scenario , appreciate direction. have scenario whereby need record assets organisation.
there various types of assets attributes differ type type there number of fields common assets such as:
location make model colour purchase_date warranty_period
similar to: how design product table many kinds of product each product has many parameters
i had through of creating
one-to_many between organisation , asset polymorhpic between asset , details class organisation < applicationrecord has_many :assets end class asset < applicationrecord belongs_to :organisation belongs :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: wish create asset & detail in single form action user after selecting asset type makes single form entry both models.
the user click link on organisation show page:
<%= link_to "new car asset", new_organisation_asset_path(@organisation, query: :new_car_asset) %>
the in controller 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 view check value of params[:query] , render corresponding form partial relates asset type.
is going down correct path or there better way achieve this? feel quite clunky.
i think maybe better use has_many :trough
, should more out of in long run. this:
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 :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
then can create assets within organisations_controller , can nest in organisation form fields_for
. assets model contain references between organisation , every single detail model, sepperate if wonna more in views or special fields.
Comments
Post a Comment