用户的未定义方法 attr_accessible 错误 [英] Undefined method attr_accessible error for User

查看:45
本文介绍了用户的未定义方法 attr_accessible 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建各种登录.我创建了一个用户脚手架并在我的 user.rb 中有此代码

I'm trying to create a login of sorts. I created a User scaffold and have this code in my user.rb

class User < ActiveRecord::Base
attr_accessible :name,  :password_digest, :password, :password_confirmation

has_secure_password
end

我一直收到这个错误

undefined method `attr_accessible' for #<Class:0x396bc28>

Extracted source (around line #2):
1
2
3
4
5

class User < ActiveRecord::Base
  attr_accessible :name,  :password_digest, :password, :password_confirmation

  has_secure_password
end

Rails.root: C:/Sites/web

推荐答案

attr_accessible 不适用于 Rails 版本 4+.您将不得不使用强参数.

attr_accessible is not available for Rails version 4+. You would have to go with strong parameters.

使用强参数,属性白名单已移至控制器级别.从您的模型中删除 attr_accessible 调用.

With Strong Parameters, attribute whitelisting has been moved to controller level. Remove the attr_accessible call from your model.

Rails 指南中的示例说明了如何使用强参数

Here is an example in Rails Guide of how to use Strong Parameters

在您的情况下,您可以执行以下操作:

In your case you can do something like this:

class UsersController < ApplicationController
  ## ...
  def create
    @user = User.new(user_params) ## Invoke user_params method
    if @user.save
      redirect_to @user, notice: 'User was successfully created.' 
    else
      render action: 'new'
    end       
  end
  ## ... 

  private
  ## Strong Parameters 
  def user_params
    params.require(:user).permit(:name, :password_digest, :password, :password_confirmation)
  end
end 

您可以在我的回答下方记下@Frederick 的评论,

You can take a note of @Frederick comment below my answer,

您仍然可以使用 attr_accessible 但它已被提取到protected_attributes gem(虽然显然强参数是前进的道路)

you can still use attr_accessible but it has been extracted into the protected_attributes gem (although clearly strong parameters is the way forwards)

这篇关于用户的未定义方法 attr_accessible 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆