ruby 在 rails 个活动记录上

ruby on rails active record

对于这种方法,我遇到了 while 循环的问题。如果我输入一个已经存在的用户名,它应该会再次提示我输入另一个用户名,但实际情况是它会跳过该部分并直接跳到提示用户输入密码。

def create_account
  # You can assign the 'get' method results to a var if you want
  puts "Enter your full name"
  get_full_name = gets.chomp

  puts 'Enter your email address'
  get_email = gets.chomp

  puts 'Enter your desired username.'
  get_username = gets.chomp

  while Customer.exists?(username: get_username) do
    puts "This username is already taken. Please enter a different one"
    get_username = gets.chomp
    break if !Customer.exists?(username: get_username)
  end

  puts "Please enter password"
  get_password = gets.chomp

  customer = Customer.create(
    first_last_name: get_full_name,
    email_address:   get_email,
    username:        get_username,
    password:        get_password)
end

只有在已有客户使用这些凭据时,您的代码才会进入循环。您能否确认具有该名称的客户已经存在,并且没有像@SujaAdiga 所暗示的那样的验证错误?

您可以使用以下方法对其进行测试:

    def create_account
  # You can assign the 'get' method results to a var if you want
  puts "Enter your full name"
  get_full_name = gets.chomp

  puts 'Enter your email address'
  get_email = gets.chomp

  puts 'Enter your desired username.'
  get_username = gets.chomp


  ## It will only enter the lop if such a customer already exists.
  ## Let's add one:

customer = Customer.create(
    first_last_name: get_full_name,
    email_address:   get_email,
    username:        get_username,
    password:        "password")

if customer.errors.full_messages.empty?
  puts "******successfully created customer*******"
  puts customer
else
  puts "*****ok we could not create the customer*****"
end

  while Customer.exists?(username: get_username) do
    puts "This username is already taken. Please enter a different one"
    get_username = gets.chomp
    break if !Customer.exists?(username: get_username)
  end

  puts "Please enter password"
  get_password = gets.chomp

  customer = Customer.create(
    first_last_name: get_full_name,
    email_address:   get_email,
    username:        get_username,
    password:        get_password)
end