Rails:当记录不存在时,记录存在回滚

时间:2015-01-01 23:29:12

标签: ruby-on-rails activerecord

我是铁杆新手。我正在尝试创建用户并在检查唯一性时获得ROLLBACK。我正在开发数据库中专门工作。我可以在索引页面上看到查询的用户,因此数据库匹配。

Started POST "/users" for 127.0.0.1 at 2015-01-01 17:02:17 -0600
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"<TOKEN THAT MATCHES THE FORM>", "user"=>{"first_name"=>"First", "last_name"=>"Test", "username"=>"test1", "email"=>"test1@self.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Create User"}
   (0.2ms)  BEGIN
  User Exists (0.4ms)  SELECT  1 AS one FROM `users` WHERE `users`.`username` = BINARY 'test1' LIMIT 1
  User Exists (0.2ms)  SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY 'test1@self.com' LIMIT 1
   (0.1ms)  ROLLBACK
  Rendered users/_form.html.erb (1.9ms)
  Rendered users/new.html.erb within layouts/application (3.8ms)
Completed 200 OK in 178ms (Views: 56.3ms | ActiveRecord: 0.9ms)

所以我检查一下我的表,看看它确实存在。

mysql> SELECT * FROM users;
+----+------------+---------------+------------------+------------+--------------------+---------------------+---------------------+
| id | first_name | last_name     | email            | username   | password_digest    | created_at          | updated_at          |
+----+------------+---------------+------------------+------------+--------------------+---------------------+---------------------+
|  1 | Initial    | User          | test0@self.com   | test0      | <SOME LONG DIGEST> | 2015-01-01 03:56:39 | 2015-01-01 03:56:39 |
+----+------------+---------------+------------------+------------+--------------------+---------------------+---------------------+
1 row in set (0.00 sec)

如果我像Rails一样运行命令:

mysql> SELECT  1 AS one FROM `users` WHERE `users`.`username` = BINARY 'test1' LIMIT 1;
Empty set (0.00 sec)

mysql> SELECT  1 AS one FROM `users` WHERE `users`.`email` = BINARY 'test1@self.com' LIMIT 1;
Empty set (0.00 sec)

它没有。为什么会发生这种情况,有没有一种好方法可以看到实际发生了什么?

2 个答案:

答案 0 :(得分:5)

我猜这很可能是一个问题:

A)模型中的验证(全部删除并再次测试) - 如果有效则一次添加一次,然后找出导致回滚的验证。

示例models / user.rb

validates :username, presence: true, uniqueness: { case_sensitive: false }

B)您错过了将要保存的其中一个属性添加到参数列表

示例controllers / users_controller.rb:

def user_params
  params.require(:user).permit(:first_name, :last_name, :email, :username, :password_digest, :_destroy)
end 

尝试(A)尝试 - 它在很多场合发生在我身上。

答案 1 :(得分:0)

您可以尝试评论您的验证(在您的模型代码中)并使用您的种子而不会出现验证问题。

但不建议这样做,因为您将在未经验证的情况下插入/操作数据。

示例:

 <textTabs>
    <text>
      <anchorString>Authorized Representative</anchorString>  -- this part does not work
      <anchorCaseSensitive>true</anchorCaseSensitive>
      <anchorIgnoreIfNotPresent>true</anchorIgnoreIfNotPresent>
      <anchorMatchWholeWord>True</anchorMatchWholeWord>
      <name>Titel_Text</name>
      <anchorXOffset>1</anchorXOffset>
      <anchorYOffset>-18</anchorYOffset>
      <anchorUnits>Pixels</anchorUnits>
    </text>
</textTabs>