Mongoid w/Rails,attr_accessible - >"找不到方法"

use*_*333 8 ruby-on-rails mongodb mongoid

  • 生成的Rails应用程序没有活动记录
  • 为Mongoid(Mongodb和Mongoid)添加了适当的宝石
  • 在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

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
Run Code Online (Sandbox Code Playgroud)

思考?

Max*_*Max 26

好的,我发现了问题.

首先,我假设你正在使用Rails 4.你得到这个错误的原因是,attr_protectedattr_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
Run Code Online (Sandbox Code Playgroud)