问题描述
在Rails 6应用程序中使用SimpleForm,我有一个嵌套对象,该对象在父对象的新方法上多次创建:
def new
@issue = @issueable.issues.new
@cat_patchvault = Catalog.find_by_slug("patchvault")
@cat_bb6 = Catalog.find_by_slug("blue-book-6")
@issue.catalog_entries.build(catalog_id: @cat_patchvault.id)
@issue.catalog_entries.build(catalog_id: @cat_bb6.id)
@issue.reorders.new
@issue.issue_variations.new
respond_with @issue
end
这些全部创建的对象和目录条目部分均被渲染,并在选择下拉列表中显示正确的目录,但是,我想更改字段集的图例以反映目录并将其移至隐藏字段。
有问题的选择
<%= form.input :catalog_id,label: 'Catalog',as: :select,prompt: 'Choose Catalog',collection: Catalog.all.order(:name),label_method: lambda { |cl| "#{cl.name} #{cl.version if cl.version}"} %>
CatalogEntry是Issue和Catalog之间的直通关系,每条记录上都有许多其他列表数据。这位于catalog_entry的嵌套字段部分中,该字段以父级形式调用:
<%= f.simple_fields_for :catalog_entries do |catalog_entry_form| %>
<%= render "catalog_entry_fields",form: catalog_entry_form %>
<% end %>
我尝试了几种不同的方法,包括SimpleForm的as: :display
(https://github.com/heartcombo/simple_form/wiki/Create-an-%22input%22-just-for-displaying-attribute-value)自定义表单类型,但是它们都破坏了表单。用javascript解决此问题似乎是错误的方法,因为属性值已经传递进来。
<%= form.association :catalog,as: :display,association_label: 'name',label: false %> Listing
如果association_label
被注释掉,它将返回一个对象,例如#<Catalog:0x00007fd7829b1098>
。如果不是,它将为nil:NilClass`返回undefined method
name',这很奇怪,因为那里有一个 对象...
解决方法
问题不在于catalog_entry_fields
。在此行调用 catalog_entry_fields
时
<%= f.simple_fields_for :catalog_entries,CatalogEntry.new,child_index: 'NEW_RECORD' do |catalog_entry_form| %>
<%= render "catalog_entry_fields",form: catalog_entry_form %>
您发送给它的 Catalog 对象没有 category_id
,因此当在 name
上调用 category_id
时,它返回 nil。如果删除此行,表单将按预期显示。
您可以通过检查自定义 object
类中的 display_input
来看到这一点。
在此处调用 display_input
类时:
<%= f.simple_fields_for :catalog_entries do |catalog_entry_form| %>
<%= render "catalog_entry_fields",form: catalog_entry_form %>
<% end %>
返回的对象是 #<CatalogEntry id: nil,catalog_id: 1,issue_id: nil,issue_type_id: nil,category_id: nil,issue_number: nil,variety: nil,combined: nil,event: false,notes: nil,created_at: nil,updated_at: nil,listed_in_error: nil,issueable_id: 5,issueable_type: "Lodge",patchscan_url: nil,slug: nil>
当 display_input
类在这里被调用时:
<%= f.simple_fields_for :catalog_entries,child_index: 'NEW_RECORD' do |catalog_entry_form| %>
<%= render "catalog_entry_fields",form: catalog_entry_form %>
表单生成器返回的对象是 #<CatalogEntry id: nil,catalog_id: nil,issueable_id: nil,issueable_type: nil,slug: nil>
没有 catalog_id,所以 name
正在 nil 上被调用,这导致了错误。