如何在Rails4中实现强参数

How to implement strong parameters in Rails 4

我在实现强参数时遇到问题,在本地收到未定义方法 attr_accessible 错误。

谁能解释一下我到底做错了什么。

users_controller.rb:

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

在user.rb中:

class User < ActiveRecord::Base
    attr_accessible :email, :password, :password_confirmation
    has_secure_password
    validates_presence_of :password, :on => :create
end

也许这是一个万无一失的解决方案...我已经尝试了很多次,但我似乎无法做到这一点。

Rails 4默认使用强参数,不需要attr_accessible。同样在 rails 4 中,您允许在控制器而不是模型中使用参数。

How is attr_accessible used in Rails 4?

strong_params 通常在控制器中完成,而不是在模型中完成。在api中也是这样描述的。所以,你也不需要设置attr_accesible。这样不同的控制器也可以在模型上设置不同的字段,例如可以允许后端用户控制器设置管理标志,而不允许前端的用户控制器这样做。

因此,您的 user_params 方法属于您的 UsersController,并且 createupdate 操作使用 user_params 过滤掉您不使用的参数' 允许设置。例如:

@user = User.new(user_params)