使用Mongoid出现“undefined method 'attr_accessible'”错误

3
我正在使用Rails 4.1.1,ruby 2.1,mongodb,mongoid作为包装器,rails_admin用于创建管理界面。
我知道在Rails4中,'attr_accessible'不再起作用。因此,我安装了 'protected_attributes' gem。但是仍然没有成功,我仍然在控制台中收到警告。
[RailsAdmin] Could not load model Company, assuming model is non existing. (undefined method `attr_accessible' for Company:Class)

因为在模型中定义了attr_accessible,所以Rails Admin没有加载Company类。以下是我的company模型。
  class Company
  include Mongoid::Document

  @@employees_strength = {0 => '0-10', 1 => '11-50', 2 => '51-100', 3 => '101-500', 4 => '501-1000', 5 => '1000+', 6 => '5000+'}

  field :name,          type: String
  field :website,       type: String
  field :domain_name,   type: String
  field :strength,      type: Integer

  has_many :employees
  has_one :admin, :class_name => 'Employee',  :dependent => :destroy, :inverse_of => :organization

  #attr_accessible :name, :website, :domain_name, :strength#, :admin_attributes, :allow_destroy => true
  attr_accessible :admin_attributes
  accepts_nested_attributes_for :admin, :allow_destroy => true
 end

请问有人可以帮忙吗? 谢谢


我知道这是一个老问题,但我遇到了同样的问题,并想分享解决方案。 - Benjamin Dobell
1个回答

2

在撰写本文时,Mongoid 4(<= 4.0.2)不了解由protected_attributes gem提供的ActiveModel::MassAssignmentSecurity模块。

因此,您必须在您的模型中手动包含该行为,例如:

class SomeDocument
  include Mongoid::Document
  include ActiveModel::MassAssignmentSecurity

  field :some_field
  attr_accessible :some_field
end

然而,这样很快就会变得繁琐,因此一个合理的替代方案是在定义任何模型之前将模块包含到Mongoid::Document模块中。
module Mongoid
  module Document
    include ActiveModel::MassAssignmentSecurity
  end
end

似乎无法与Rails 4一起使用:未初始化常量ActiveModel :: MassAssignmentSecurity - Lev Denisov
@LevDenisov 如上所述,它是由 protected_attributes gem 提供的,它不随 Rails 4 一起提供 - 您必须将其添加到您的 Gemfile 中。 - Benjamin Dobell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接