Mongoid w / Rails,attr_accessible – >“找不到方法”
- 生成的Rails应用程序没有活动记录
- 为Mongoid(Mongodb&Mongoid)添加了合适的gem
- 在config / with rails support中生成mongoid.yml文件
- 创建了具有典型CRUD路由的朋友模型和用户控制器
一切都有效,除非我尝试进行质量分配,我得到: "undefined method `attr_accesible' for Friend:Class"
型号,friend.rb:
class Friend include Mongoid::Document field :first_name, :type => String field :last_name, :type => String field :adjective, :type => String attr_accessible :first_name, :last_name, :adjective end
class Friend include Mongoid::Document field :first_name, :type => String field :last_name, :type => String field :adjective, :type => String attr_accessible :first_name, :last_name, :adjective end
development: sessions: default: database: first_development hosts: - localhost:27017 options: options: test: sessions: default: database: first_test hosts: - localhost:27017 options: consistency: :strong max_retries: 1 retry_interval: 0
思考?
好的,我发现了问题。
首先,我假设你正在使用Rails 4.你得到这个错误的原因是attr_protected
和attr_accessible
已经从Rails 4中删除并放在他们自己的gem中。 Rails现在正在鼓励一种新的保护模式。 您可以在README中阅读相关内容。 如果要继续使用旧行为,则必须包含protected_attributes gem 。 希望有所帮助。
编辑:我在下面添加了说明,因为这可能是用户升级到rails 4的常见问题。
如果您想继续使用attr_accessible
,即Rails 3方式,只需将gem protected_attributes
添加到Gemfile即可。
如果您想开始使用Rails 4方式,则必须不再使用attr_accessible
。 相反,您必须将属性权限逻辑移动到控制器中。 这是一个例子:
class UsersController < ApplicationController def create # Using params[:user] without calling user_params will throw an error because # the parameters were not filtered. This is just some Rails magic. @user = User.new user_params if @user.save # Do whatever else render action: :new end end private def user_params # params.require(:user) throws an error if params[:user] is nil if current_user.nil? # Guest # Remove all keys from params[:user] except :name, :email, :password, and :password_confirmation params.require(:user).permit :name, :email, :password, :password_confirmation elsif current_user.has_role :admin params.require(:user).permit! # Allow all user parameters elsif current_user.has_role :user params.require(:user).permit :name, :email, :password, :password_confirmation end end
对于使用Rails 5并且发现protected_attributes gem
不兼容的任何读者:
您不需要attr_accessible
因为不再可以进行质量分配https://www.rubyplus.com/articles/3281-Mass-Assignment-in-Rails-5
- US-ASCII中的无效字节序列(Ruby 1.9 + rails 2.3.8 + mongodb + mongo_mapper)
- 使用mongoid / mongodb提取,建模和更改数据模型
- Ruby超级不敏感的Regex,用于将学校名称与重音和其他变音符号相匹配
- 使用MongoMapper创建用于编辑嵌入文档的表单
- Rails + MongoMapper + EmbeddedDocument形成帮助
- 在Ruby on Rails 3.2中使用Mongo DB会话存储时如何清除旧/陈旧会话
- Mongoid排序模型基于数组大小,在其他Model(has_one)关系中
- MongoDB不会使用Mongoid连接到MongoHQ
- 查询Mongoid / rails 3中的嵌入对象(“低于”,Min运算符和排序)