[英]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.