Ruby on rails 如何在Rails 4中实现强参数
我在实现强参数时遇到问题,在本地接收到未定义的方法attr_accessible error 谁能解释一下我到底做错了什么 用户\u controller.rb:Ruby on rails 如何在Rails 4中实现强参数,ruby-on-rails,ruby,ruby-on-rails-4,strong-parameters,Ruby On Rails,Ruby,Ruby On Rails 4,Strong Parameters,我在实现强参数时遇到问题,在本地接收到未定义的方法attr_accessible error 谁能解释一下我到底做错了什么 用户\u controller.rb: class UsersController < ApplicationController def new @user = User.new end def create @user = User.new(user_params) if @user.sav
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
def user_params
params.require(:user).permit(:username, :email, :password, :password_confirmation)
end
end
class UsersController“已注册!”
其他的
呈现“新”
结束
结束
def用户参数
参数require(:user).permit(:用户名,:电子邮件,:密码,:密码\u确认)
结束
结束
在user.rb中:
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation
has_secure_password
validates_presence_of :password, :on => :create
end
class用户:create
结束
也许这是一个万无一失的解决方案……我尝试了很多次,但似乎都做不好。Rails 4默认使用强参数,您不需要attr\u访问。同样在rails 4中,您允许控制器中的参数而不是模型中的参数
强参数通常在控制器中完成,而不是在模型中完成。书中也有这样的描述。因此,也不需要设置
attr\u accessible
。这样,不同的控制器也可以在模型上设置不同的字段,例如,允许后端用户控制器设置管理标志,而不允许前端的用户控制器这样做
因此,您的用户参数
方法属于用户控制器
,而创建
和更新
操作使用用户参数
过滤掉不允许设置的参数。e、 g:
@user = User.new(user_params)
那么,我可以删除其中包含attar_accessible的行吗?不需要attr_accessible,只需在新操作中使用user_参数即可。我会更新我的答案。它是固定的,我想现在接受这个答案。将运行更多的测试。