微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ruby-on-rails – Mongoid w / Rails,attr_accessible – >“找不到方法”

>生成的Rails应用程序没有活动记录
>为Mongoid( Mongodb& Mongoid)添加了适当的宝石
>在config / with rails support中生成mongoid.yml文件
>创建了具有典型CRUD路线的朋友模型和用户控制器

一切正常,除非我尝试进行大规模任务,我得到:
“朋友的未定义方法`attr_accesible’: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

思考?

解决方法

好的,我发现了问题.

首先,我假设你正在使用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,: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,:password_confirmation
    end
  end

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐