![](/img/trans.png)
[英]Rails has_one/belongs_to associations not working as expected
[英]Rails Polymorphic Associations has_one / belongs_to
我有以下情況:
我有一個名為“ ConfigurationItem”的模型。
class ConfigurationItem < ActiveRecord::Base
belongs_to :contract_asset
belongs_to :provider
belongs_to :configuration, polymorphic: true
validate :name, :contract_asset, presence: true
end
然后我暫時有兩個模型,“ OsConfiguration”和“ HardwareConfiguration”
class OsConfiguration < ActiveRecord::Base
has_one :configuration_item, as: :configuration
end
class HardwareConfiguration < ActiveRecord::Base
has_one :configuration_item, as: :configuration
end
在創建過程中,我首先采用ConfigurationItem的形式。 所以我的問題是,如何從ConfigurationItem表單中創建操作系統或硬件配置。 像這樣:
到目前為止,我嘗試的是這樣的路由:
resources :configuration_items do
resources :os_configurations
resources :hardware_configurations
end
但是其余的內容對我來說有點沉重(我對Rails非常陌生)。
另外,我正在使用這個gem: https : //github.com/codez/dry_crud
編輯:
更具體地說,我可以從configurationItem表單中選擇操作系統或硬件配置。 如果我選擇os配置,則會在其表單中顯示一個模式表單。 保存Os Configuration時,必須使用先前的格式設置其屬性configuration_item,因此尚未創建他,並且無法從os配置的控制器訪問它。
就像在rails_admin中一樣,您可以從表單中創建和添加其他模型的新實例。
謝謝 !
這是我的解決方案,在ConfigurationItem的列表視圖中,添加了下拉菜單
%ul.dropdown-menu.pull-right
- ConfigurationItemsController::ITEM_TYPES.keys.each do |type|
%li= link_to("Add #{type.titleize} Item", new_contract_contract_asset_configuration_item_path(@contract, @contract_asset, type: type))
在我的ConfigurationItemsController中,使用下拉列表類型創建配置。
ITEM_TYPES = { 'plain' => nil,
'os' => OsConfiguration,
'hardware' => HardwareConfiguration }
before_filter :assign_configuration_type, only: [:new, :create]
def assign_configuration_type
if type = ITEM_TYPES[params[:type]]
entry.configuration = type.new
end
end
def models_label(plural = true)
if @configuration_item
if config = @configuration_item.configuration
"#{config.class.model_name.human.titleize} Item"
else
"Plain Configuration Item"
end
else
super(plural)
end
end
在我的ConfigurationItem的表單視圖中,我用配置的字段擴展表單
- if entry.new_record?
= hidden_field_tag :type, params[:type]
- if @configuration_item.configuration
= f.fields_for(:configuration) do |fields|
= render "#{@configuration_item.configuration.class.model_name.plural}/fields", f: fields
因此,我在表單之前選擇要擁有的配置,而不是在表單中。
在創建對象的configuration_items_controller中,從下拉輸入中檢查選擇,然后根據設置為創建該對象的設置進行檢查。
def create
item = ConfigurationItem.new
... do what you need to here ...
item.save
if (params[:dropdown]=='OS Configuration')
os_config = OSConfiguration.new
... do what you need to ...
os_config.configuration_id = item.id
os_config.save
elseif (params[:dropdown]=='Hardware Configuration')
hardware_config = HardwareConfiguration.new
... do what you need to ...
hardware_config.configuration_id = item.id
hardware_config.save
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.