环境:
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>