2017-06-02 124 views
0

我想用Rails 5和Mongoid做一个简单的用户注册功能。我的用户模型和控制器是这样的:Rails 5 + Mongoid虚拟属性

user.rb

class User 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    validates_presence_of :email 
    validates_uniqueness_of :email, case_sensitive: false 

    validates :password, presence: true, confirmation: true 
    validates_presence_of :password_confirmation 

    field :email, type: String 
    field :password, type: String 
    ... 
end 

users_controller.rb

... 
def create 
    @user = User.new(user_params) 
    if @user.save 
    json_response(nil, nil, :created) 
    else 
    json_response(@user.errors.full_messages, nil, :bad_request) 
    end 
end 
... 
private 
    def user_params 
    params.require(:user).permit(:email, :password, :password_confirmation, :avatar) 
    end 

现在我需要检查,如果password_confirmation相同的密码,无论是PARAMS通过请求发送,但password_confirmation不传递给新的用户对象,altought在强参数中列入白名单:

log:

Started POST "/users" for 127.0.0.1 at 2017-06-02 13:03:10 +0200 
Processing by UsersController#create as JSON 
Parameters: {"password"=>"[FILTERED]", email"=>"[email protected]", "password_confirmation"=>"[FILTERED]", "user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}} 

我不想

field :password_confirmation 

添加到我的模型,解决了这个问题。我只需要使属性成为虚拟并在验证后摆脱它。我错过了什么或做错了什么?或者对此有何正确态度?

回答

0

在你的模型,其添加为attr_acessor

Class User 
... 
field :email, type: String 
field :password, type: String 
attr_accessor :password_confirmation 
... 
end 

您可以访问它,但它不会持久。

+0

不幸的是,这似乎没有帮助,似乎''params.require(:user).permit(...)'只能与'field'定义的那些属性一起工作,并忽略'attr_accessor' –

+0

好吧,作为最后一招你可以添加它作为一个字段,但通过创建一个before_save过滤器来避免它被保存为零。这很丑,但会起作用。 –

+0

当然,还有更多“肮脏”的解决方案,但我想做的很好,干净... –