0

だから、これは私を夢中にさせており、自分自身でも他の質問と回答を読んでも質問に答えることができないことに気づきました.

Web アプリケーションで作成されたデータベースのレコードを更新しようとすると、レコードの値を変更できません。この場合、ユーザーが入力するフォームがあり、その後、アプリは異なるモデルのいくつかのフィールドを更新する必要があります。

まず、フォーム:

<%= 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 %>

Games コントローラーには create メソッドがあります

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 

なぜユーザーが有効であってはならないのか理解できません。すべてのテストに合格します (railstutorial の方法で定式化されます)。私のユーザーモデル:

# == 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

4 に答える 4

1

それらがupdate_attributesであるときはいつでも、パスワードを更新しようとします。これにより、レコードが無効になります。

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

今それを試してみてください

于 2012-09-28T13:31:39.140 に答える
0

DB内のデータが不十分なため、有効ではない可能性があります(一部のユーザーは同じメールアドレスまたは名前を持っています)。この場合は、データベースをリロードしてください

于 2012-09-28T13:33:38.317 に答える
0

それを書く別の方法。

with_options if: :password do |user|
  user.validates :password, presence: true, length: { minimum: 6 }
  user.validates :password_confirmation, presence: true
end
于 2013-01-25T21:29:40.103 に答える
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
于 2012-09-28T13:45:00.163 に答える