[英]Rails undefined method `map' for nil:NilClass on collection_select - The reference called may be nil
After reading through the other SO answers, it's pretty clear that there are some common themes. 仔细阅读其他SO答案后,很显然有一些共同的主题。
Mostly this type of error seems to happen when the object called is not defined yet, but in this case we have a has_many
relationship that may not have a referenced entry when building the selection. 通常,当尚未定义调用的对象时,似乎会发生这种类型的错误,但是在这种情况下,我们具有has_many
关系,在建立选择时可能没有引用的条目。
Class Tag
property :name, type: String
has_many :in, :tagged, type: :CONCEPTUAL_TAG, model_class: :Artefact
end
One option is to do something like this: 一种选择是执行以下操作:
<div class="field">
<%= f.label :tagged_id %><br>
<% if !@tag.tagged.empty? %>
<%= f.collection_select(:tagged, Artefact.all.sort { |a,b| a.name <=> b.name }, :id, :name, options = {:prompt => "Please Select an Item", :selected => @tag.tagged.map(&:id)}, html_options = {:multiple => true, :class=>"search"}) %>
<% else %>
<%= f.collection_select(:tagged, Artefact.all.sort { |a,b| a.name <=> b.name }, :id, :name, options = {:prompt => "Please Select an Item"}, html_options = {:multiple => true, :class=>"search"}) %>
<% end %>
</div>
But this is definitely not DRY. 但这绝对不是DRY。
Is there a way to select nothing when there is no association, and pre-populate when there is while keeping to a single f.collection_select
? 有没有办法在没有关联的情况下什么也不选择,而在保持单个f.collection_select
预先填充?
You don't have to use the condition in your view. 您不必在视图中使用该条件。 Even if there are no items in @tag.tagged
, it is still an ActiveRecord::Relation
instance, so you can go ahead and just call map
on it: 即使@tag.tagged
中没有任何项目,它仍然是一个ActiveRecord::Relation
实例,因此您可以继续在其上调用map
:
<%= f.collection_select(:tagged,
Artefact.all.sort { |a,b| a.name <=> b.name },
:id,
:name,
options = {
:prompt => "Please Select an Item",
:selected => @tag.tagged.map(&:id)
},
html_options = {
:multiple => true,
:class=>"search"
})
%>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.