Ruby on Rails的时候产生失败的Active Record返回值? [英] Ruby on Rails Active Record return value when create fails?

查看:112
本文介绍了Ruby on Rails的时候产生失败的Active Record返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的Ruby on Rails和遇到了麻烦这项工作。基本上我有一个用户注册网页,其中有一个密码确认。在用户级的,我有以下验证:

I am new to ruby on rails and having trouble getting this work. Basically I have a user registration page which has a password confirmation. In the User class I have the following validation:

validates :password, confirmation: true

和控制器我有

def create
    vals = params[:user]
    if(User.exists(vals[:username])) 
        flash[:warning] = "#{vals[:username]} already exists! Please try a new one. "
    else
        vals[:create_date] = DateTime.current
        user = User.create(vals, :without_protection => :true)
        if user==false or user==nil or user==vals
            flash[:warning] = "#{vals[:username]} has not been registered successfully. "
        else
            flash[:notice] = "#{vals[:username]} has been registered. "
        end
    end
    redirect_to users_path
end

现在的问题是,当密码不匹配确认,我仍然得到显示,注册成功的通知消息。正如你可以看到我已经尝试了几种返回值创建,但他们都不似乎成功。我是pretty的确保验证工作,因为我看不到我刚刚创建的,如果密码不与确认匹配用户。此外,当我使用创造!,我可以看到的网站崩溃,并验证错误。谁能帮告诉我是什么创建应在记录未验证的回报?

The problem is that when the password does match the confirmation, I am still getting the notice message showing that the registration is successful. As you can see I have tried several return values for create but none of them seems to succeed. I am pretty sure that the validation is working because I cannot see the user that I just created if password does not match with confirmation. In addition, when I use create!, I can see the website crashes with the validation error. Can anyone help telling me what create should return when the record is not validated?

感谢。

推荐答案

在回答你的问题是, User.create 返回用户举例来说,如果它成功的的失败。如果它失败,因为验证的,实例将是无效的,将有错误的:

The answer to your question is, User.create returns a User instance if it succeeds or fails. If it fails because of validations, the instance will be invalid and will have errors:

user.valid? # <= returns false
user.errors.count # <= will be > 0
user.errors.blank? # <= will be false

所以,你的code将改变从这样的:

So your code would change from this:

if user==false or user==nil or user==vals

这样:

if !user.valid?

您也可以使用此模式:

user.attributes = vals
if user.save
   ... save succeeded ...
else
   ... save failed ...
end

保存方法返回一个布尔虚假正确的,因为你是在现有的实例调用它。

The save method returns a boolean true of false since you are calling it on an existing instance.

但是让我们让你在正确的轨道在其他几个方面:

But lets get you on the right track in a few other ways:

第一:你有这样的:

if User.exists(vals[:username])

(我假设退出是你把你的用户的方法模式,因为这不是一个Rails的东西)。相反,这样做,检查你的控制器,你可以使用另一个验证型号:

(I'm assuming exits is a method you put on your User model because that's not a Rails thing). Instead of doing that check in your controller, you can just use another validation on the model:

class User < ActiveRecord::Base
   ...
   validates :username, unique: true
   ...
end

现在,当您尝试创建用户,将无法通过验证,如果你已经有一个用这个名字。

Now when you try to create the user, it will fail validation if you already have one with that name.

二:您有这样的:

vals[:create_date] = DateTime.current

这是不必要的。如果一列添加到模型中名为 created_at 将举办创建日期自动(通过ActiveRecord的管理)。您可以添加这个,和它的合作伙伴的updated_at 你在这样的迁移模式:

This is unnecessary. If you add a column to your model called created_at it will hold the creation date automatically (managed by ActiveRecord). You can add this, and its partner updated_at to your model in your migration like this:

create_table :users do |t|
   ...
   t.timestamps # <= tells rails to add created_at and updated_at
end

或者,因为你已经有一个用户表:

add_column :users, :created_at, :datetime
add_column :users, :updated_at, :datetime

现在,你将永远有创建和最近更新的日期/时间,而无需额外的code用户模式。

Now you will always have the date/time of creation and last update on your user model with no need for additional code.

三:您有这样的:

user = User.create(vals, :without_protection => :true)

不要这样做。相反,改变这种:

Don't do this. Instead, change this:

vals = params[:user]

要这样:

vals = params.require(:user).permit(:username, :password, :password_confirmation)

然后再继续保护上:

And then keep protection on:

user = User.create(vals)

您可以添加您想从您的窗体带来的许可()调用任何其他列。这是非常重要的,因为这是很难后来解决这种事情。 如果一旦你走了黑暗之路,将永远是主宰你的命运。

You can add any additional columns you want to bring from your form to the permit() call. This is very important because it is hard to fix this kind of thing later. "If once you go down the dark path, forever will it dominate your destiny."

第四::您不应该重定向到user_path如果保存失败,因为不会有用户模式显示。相反,你应该重新呈现你的的形式。你也不必为错误的提示信息。如果的形式呈现,它可以检查 @ user.errors 和报错信息相应。请参阅 ActiveRecord的错误对象文档

Fourth: You should not redirect to the user_path if the save failed, because there will be no user model to show. Instead you should re-render your new form. You also don't need flash messages for the errors. If the new form renders, it can check @user.errors and report error messages accordingly. See the ActiveRecord error object documentation.

最后::您提到,即使密码正确确认您在验证失败。没有看到你的形式code,我不能肯定地说,但要确保你的密码字段被称为密码和确认域中被称为 password_confirmation 。 Rails将这个 * _确认字段值专验证确认时。

Finally: You mention that you your validation fails even when your password is properly confirmed. I can't say for sure without seeing your form code, but make sure your password field is called password and the confirmation field is called password_confirmation. Rails looks for this *_confirmation field value specifically when validating for confirmation.

如果不这样做,发表您的形式code,我会修改。

If that doesn't do it, post your form code and I'll revise.

这篇关于Ruby on Rails的时候产生失败的Active Record返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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