繁体   English   中英

ruby on 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM