更新db中的记录会使记录无效吗?

时间:2012-09-28 13:00:47

标签: ruby-on-rails model console record updating

所以,这让我发疯,我发现自己也无法自己回答这个问题,也无法回答其他问题和答案。

当我尝试更新通过webapp创建的数据库中的记录时,我无法更改记录的值。在这种情况下,有一个用户填写的表单,之后应用程序应该更新不同模型中的几个字段。

首先,形式:

<%= form_for(@game) do |g| %>
  <%= g.label :player_1 %>
  <%= g.text_field :player_1 %>

  <%= g.label :player_2 %>
  <%= g.text_field :player_2 %>

  <%= g.label :faction_1 %>
  <%= g.text_field :faction_1 %>

  <%= g.label :faction_2 %>
  <%= g.text_field :faction_2 %>

  <%= g.label :caster_1 %>
  <%= g.text_field :caster_1 %>

  <%= g.label :caster_2 %>
  <%= g.text_field :caster_2 %>

  <%= g.label :point_level %>
  <%= g.text_field :point_level %>

  <%= g.label :winner %>
  <%= g.text_field :winner %>

  <%= g.submit "eintragen", class: "btn btn-large btn-primary" %>
<% end %>

在游戏控制器中,我有一个创建方法

def create
    @game = Game.new(params[:game])
    if @game.save
      flash[:success] = "Spiel erfolgreich eingereicht"
      @player_1 = User.find_by_name(@game.player_1)
      @player_1.update_attributes(:games_played => @player_1.games_played + 1)
      redirect_to @game
    else
      render 'new'
    end
 end

毋庸置疑,它并没有像我预期的那样发挥作用。我的错误如下:如果我尝试在控制台中更改记录,则会发生以下情况:

user = User.find_by_name("Example User")
User Load (0.2ms)  SELECT "users".* FROM "users" WHERE "users"."name" = 'Example User' LIMIT 1
=> #<User id: 1, name: "Example User", email: "example@railstutorial.org", created_at: "2012-09-28 11:48:10", updated_at: "2012-09-28 11:48:10", password_digest: "$2a$10$3GQnsHGAfp09v1v.csb6Ce8pCPwfY0Hl1nG2a09BvOo8...", remember_token: "MsRfXle0N67ws9otkeDP_w", admin: true, elo_rating: 1000, games_played: 0> 


user.valid?
  User Exists (0.2ms)  SELECT 1 AS one FROM "users" WHERE (LOWER("users"."name") = LOWER('Example User') AND "users"."id" != 1) LIMIT 1
  User Exists (0.1ms)  SELECT 1 AS one FROM "users" WHERE (LOWER("users"."email") = LOWER('example@railstutorial.org') AND "users"."id" != 1) LIMIT 1
=> false 

我无法理解为什么用户不应该有效。所有测试都通过(以铁路指导的方式制定)。我的用户模型:

# == Schema Information
#
# Table name: users
#
#  id              :integer          not null, primary key
#  name            :string(255)
#  email           :string(255)
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#  password_digest :string(255)
#  remember_token  :string(255)
#  admin           :boolean          default(FALSE)
#  elo_rating      :integer          default(1000)
#  games_played    :integer          default(0)
#

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation, :games_played, :elo_rating
  has_secure_password

  before_save { |user| user.email = email.downcase }
  before_save :create_remember_token
  validates :name,  presence: true, 
                    uniqueness: true, 
                    length: { :maximum => 50 }

  # regex take from railstutorial by Michael Hartl (http://ruby.railstutorial.org)
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, presence: true, 
                    format: { with: VALID_EMAIL_REGEX },
                    uniqueness: { case_sensitive: false }

  validates :password, presence: true, length: { minimum: 6 }
  validates :password_confirmation, presence: true
  validates :games_played, presence: true
  validates_numericality_of :games_played, greater_than_or_equal_to: 0
  validates_numericality_of :elo_rating, greater_than_or_equal_to: 0

  private

    def create_remember_token
      self.remember_token = SecureRandom.urlsafe_base64
    end
end

我真的被困在这里,因为这个功能是必不可少的,我必须通过表单进行更多这些记录更新。我真的无法弄清楚为什么我的记录无效。此外,我确信有更好的方法可以更新这些记录,甚至可以完全避免这个问题吗?

提前致谢

4 个答案:

答案 0 :(得分:1)

只要他们是update_attributes itt尝试更新密码也会使记录无效只是做

validates :password, presence: true, length: { minimum: 6 }, :if => :password
validates :password_confirmation, presence: true, :if => :password_confirmation

现在试试吧

答案 1 :(得分:0)

由于数据库中的数据不佳(某些用户拥有相同的电子邮件或名称),可能无效。如果是这种情况,请重新加载数据库

答案 2 :(得分:0)

根据您的user.errors,您不希望每次保存用户时都验证:password和:password_confirmation;只有当您实际创建用户或允许用户明确更新这些值时,例如从他们的帐户编辑页面开始。

如果您进行如下更改,您的用户模型验证逻辑可能会起作用:

class User < ActiveRecord::Base
  validates :password, presence: {if: :password_required?}, length: { minimum: 6, allow_blank: true }
  validates :password_confirmation, presence: { if: :password_required? }

  private

  def password_required?
    !persisted? || !password.nil? || !password_confirmation.nil?
  end
end

答案 3 :(得分:0)

另一种写作方式。

with_options if: :password do |user|
  user.validates :password, presence: true, length: { minimum: 6 }
  user.validates :password_confirmation, presence: true
end