gpt4 book ai didi

ruby-on-rails - 用户的未定义方法 attr_accessible 错误

转载 作者:数据小太阳 更新时间:2023-10-29 07:21:10 26 4
gpt4 key购买 nike

我正在尝试创建某种登录。我创建了一个用户脚手架,并将这段代码放在我的 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 version 4+。您将不得不使用强大的参数。

有了强参数,属性白名单已移至 Controller 级别。从您的模型中删除 attr_accessible 调用。

这是 Rails 指南中关于如何使用 Strong Parameters 的示例

在你的情况下你可以这样做:

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 still use attr_accessible but it has been extracted into the protected_attributes gem (although clearly strong parameters is the way forwards)

关于ruby-on-rails - 用户的未定义方法 attr_accessible 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23743603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com