【问题标题】:ruby on rails active recordruby on rails 活动记录
【发布时间】:2019-10-17 05:09:15
【问题描述】:

对于这种方法,我遇到了 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

【问题讨论】:

  • 你确定Customer.create是否成功执行?
  • 你为什么不使用 ActiveRecord 的验证来代替 Costumer.exists?健康)状况?您可以改为设置用户名的唯一性并循环,直到该属性没有错误为止。

标签: ruby-on-rails ruby rails-activerecord


【解决方案1】:

只有在已有客户拥有这些凭据时,您的代码才会进入循环。您能否确认已存在具有该名称的客户,并且不存在像 @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

【讨论】:

    猜你喜欢
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 2013-03-26
    • 1970-01-01
    • 2012-04-18
    相关资源
    最近更新 更多