Gem simple_form+mongoid 表关联遇到问题

suupic · 2011年12月21日 · 最后由 Jsiguo 回复于 2012年02月04日 · 3600 次阅读

错误:undefined method `options' for #Mongoid::Relations::Metadata:0x00000003742388

基于 mongoid

在 User 模型中

has_and_belongs_to_many :group

在 Group 模型中

has_and_belongs_to_many :user

表单视图

<%= simple_form_for(@group) do |f| %>
  <% if @group.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@group.errors.count, "error") %> prohibited this group from being saved:</h2>

      <ul>
      <% @group.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

    <%= f.label :name, :label => '名称' %>
    <%= f.input_field :name %>
    <%= f.association :user %>
    <%= f.button :submit, :value => '创建用户组' %>
<% end %>

出错在这一句

<%= f.association :user %>

换了 formtastic 也有同样的问题 看起来是 mongoid 哪里不对劲

console 里关联关系无异常

Reloading...
=> true
irb(main):097:0> u=User.new 
=> #<User _id: 4ef1bd5d53cd2108dd000008, _type: nil, created_at: nil, updated_at: nil, name: nil, email: nil, mobile: nil, tel: nil, alias: nil, birthday: nil, second_email: nil, address: nil, company: nil, memo: nil, plan_ids: [], group_ids: []>
irb(main):098:0> g=Group.new
=> #<Group _id: 4ef1bd6753cd2108dd000009, _type: nil, created_at: nil, updated_at: nil, name: nil, user_ids: []>
irb(main):099:0> u.group << g
=> []
irb(main):100:0> u.group
=> [#<Group _id: 4ef1bd6753cd2108dd000009, _type: nil, created_at: nil, updated_at: nil, name: nil, user_ids: [BSON::ObjectId('4ef1bd5d53cd2108dd000008')]>]
irb(main):101:0> g
=> #<Group _id: 4ef1bd6753cd2108dd000009, _type: nil, created_at: nil, updated_at: nil, name: nil, user_ids: [BSON::ObjectId('4ef1bd5d53cd2108dd000008')]>
irb(main):102:0> 

没遇到过。。。先试试单纯的 user belongs_to group 试试? 或者你可以试着看看 simple_form 里有关 association 的代码 https://github.com/plataformatec/simple_form/blob/master/lib/simple_form/form_builder.rb

需要 登录 后方可回复, 如果你还没有账号请 注册新账号