Rails mongoid dynamic fields - no method error

时光怂恿深爱的人放手 提交于 2019-12-25 03:37:22

问题


ENV:

Rails-3.2.12

Ruby-1.9.3

Mongoid-3.1.1

I have model:

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

but if I try to add dynamic field in view, lets say "color", i get an undefined method error.

allow_dynamic_fields: true is enabled in the config file.

_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>

everything works fine if I try to edit item which already have color attribute. I need to add several dynamic attributes which depends on item.type but without something like this:

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

EDIT:

Error:

NoMethodError in Items#new

Showing /app/views/items/_form.html.erb where line #31 raised:

undefined method `color' for # Extracted source (around line #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>

回答1:


Mongoid docs says:

"If the attribute does not already exist on the document, Mongoid will not provide you with the getters and setters and will enforce normal method_missing behavior. In this case you must use the other provided accessor methods: ([] and []=) or (read_attribute and write_attribute). "

The easiest thing you can do is to set 'color' in your controller #new method using write_attribute or []=

@item['color'] = ''

Or you can just dynamically add 'color' attribute to your new Item singleton class:

class << @item
  field :color, type: String
end


来源:https://stackoverflow.com/questions/14939111/rails-mongoid-dynamic-fields-no-method-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!