0

环境:

Rails-3.2.12

Ruby-1.9.3

Mongoid-3.1.1

我有模型:

class Item
   include Mongoid::Document
   field :name, type: String
   field :type, type: String
end

但是如果我尝试在视图中添加动态字段,比如说“颜色”,我会得到一个未定义的方法错误。

allow_dynamic_fields: true在配置文件中启用。

_form.html.erb:

<%= form_for(@item) do |f| %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
<div class="field">
  <%= f.label :type %><br />
  <%= f.text_field :type %>
</div>
<div class="field">
  <%= f.label :color %><br />
  <%= f.text_field :color %>
</div>

如果我尝试编辑已经具有颜色属性的项目,一切正常。我需要添加几个取决于 item.type 但没有这样的动态属性:

<% if @item[:color] %>
  <%= f.text_field :color %>
<%else%>
  <%= text_field_tag 'item[color]' %>
<% end %>

编辑:

错误:

项目中的 NoMethodError#new

显示第 31 行引发的 /app/views/items/_form.html.erb :

#Extracted source 的未定义方法“color”(在第 31 行附近):

28:     <%= f.number_field :type %>
29:   </div>
30:    <%= f.label :color %><br />
31:     <%= f.text_field :color %>
32:     <div class="actions">
33:       <%= f.submit %>
34:     </div>
4

1 回答 1

0

Mongoid 文档说:

“如果文档中不存在该属性,Mongoid 将不会为您提供 getter 和 setter,并将强制执行正常的 method_missing 行为。在这种情况下,您必须使用其他提供的访问器方法:([] 和 []=) 或(read_attribute 和 write_attribute)。”

您可以做的最简单的事情是使用 write_attribute 或 []= 在控制器#new 方法中设置“颜色”

@item['color'] = ''

或者您可以将“颜色”属性动态添加到您的新 Item 单例类中:

class << @item
  field :color, type: String
end
于 2013-02-18T15:45:48.860 回答