用户验证&在视图中显示错误消息

时间:2015-06-29 01:35:30

标签: ruby validation activerecord sinatra

这适用于使用Sinatra和ActiveRecord的应用。我正在尝试在我的视图文件(_form.erb)上显示一条错误消息,但Sinatra只显示“我不知道这个小曲”消息,并且不会在页面上显示实际的错误消息。 / p>

这是一个用户应该输入名字,姓氏和生日的表格。 “validates_presence_of:birthdate,:first_name,:last_name”应该检查字段是否为空,但我不确定我是否实际执行了这样的代码,这就是错误消息未显示的原因。特别是,下面的后期路线部分有:

if params[:birthdate].include?("-")
        birthdate = params[:birthdate]
    else
        birthdate = Date.strptime(params[:birthdate], "%m%d%Y")
end

假设总是有输入,所以如果你将birthdate字段留空并且不会显示错误消息,那么Sinatra会说“ArgumentError:invalid date”。我不确定如何让Sinatra停止为birthdate字段提供该错误并在页面上显示错误消息,但如果我输入生日并将名称字段留空,则不会显示错误消息。

这是我的people_controller.rb文件中的相关路线:

#create a new person
#if-else clause accounts for date input with dashes and without dashes (string input)
post "/people" do
    if params[:birthdate].include?("-")
        birthdate = params[:birthdate]
    else
        birthdate = Date.strptime(params[:birthdate], "%m%d%Y")
    end

    @person = Person.new(first_name: params[:first_name], last_name: params[:last_name], birthdate: birthdate)
    if @person.valid?
        @person.save
        redirect "/people/#{@person.id}"
    else
        @error = "The data you entered isn't valid"
        erb :"/people/new"
    end
end

这是我的people / new.erb文件:

<h1>Create a Person</h1>
<%= erb :"/people/_form" %>

这是我的人/ _form.erb文件:

<% if !@errors.blank? %>
  <p class="errors">
    <%= "#{@errors}" %>
  </p>
<% end %>
<form action="<%= people_form_action(@person) %>" method="post" id="<%= people_form_id(@person) %>" class="<%= people_form_class(@person) %>">
  <input type="hidden" name="_method" value="<%= people_form_method(@person) %>" />
  <div>
    <label for="first_name">First Name:</label>
    <input type="text" name="first_name" value="<%= @person.first_name %>" />
  </div>

  <div>
    <label for="last_name">Last Name:</label>  
    <input type="text" name="last_name" value="<%= @person.last_name %>" />
  </div>

  <div>
    <label for="birthdate">Birthdate:</label>
    <input name="birthdate" type="date" value="<%= @person.birthdate %>" />
  </div>

  <div>
    <input type="submit" />
  </div>
</form>

这是我的Person类:

class Person < ActiveRecord::Base

    validates_presence_of :birthdate, :first_name, :last_name

    def self.get_birth_path_num(birthdate)

        number = birthdate[0].to_i + birthdate[1].to_i + birthdate[2].to_i + birthdate[3].to_i + birthdate[4].to_i + birthdate[5].to_i + birthdate[6].to_i + birthdate[7].to_i
        number = number.to_s
        number = number[0].to_i + number[1].to_i

        if(number > 9)
            number = number.to_s
            number = number[0].to_i + number[1].to_i
        end

        return number
    end


    def self.get_message(number)
        case(number)
            when(1)
                message = "One is the leader. The number one indicates the ability to stand alone, and is a strong vibration. Ruled by the Sun."
            when(2)
                message = "This is the mediator and peace-lover. The number two indicates the desire for harmony. It is a gentle, considerate, and sensitive vibration. Ruled by the Moon."
            when(3)
                message = "Number Three is a sociable, friendly, and outgoing vibration. Kind, positive, and optimistic, Three's enjoy life and have a good sense of humor. Ruled by Jupiter."
            when(4)
                message = "Your numerology number is 4. This is the worker. Practical, with a love of detail, Fours are trustworthy, hard-working, and helpful. Ruled by Uranus."
            when(5)
                message = "This is the freedom lover. The number five is an intellectual vibration. These are 'idea' people with a love of variety and the ability to adapt to most situations. Ruled by Mercury."
            when(6)
                message = "This is the peace lover. The number six is a loving, stable, and harmonious vibration. Ruled by Venus."
            when(7)
                message = "This is the deep thinker. The number seven is a spiritual vibration. These people are not very attached to material things, are introspective, and generally quiet. Ruled by Neptune."
            when(8)
                message = "This is the manager. Number Eight is a strong, successful, and material vibration. Ruled by Saturn."
            when(9)
                message = "This is the teacher. Number Nine is a tolerant, somewhat impractical, and sympathetic vibration. Ruled by Mars."
        end
    end

    #method to check if a user enters a valid birthdate
    def self.valid_birthdate(input)
        if(input.length==8 && input.match(/^[0-9]+[0-9]$/))
            return true
        else
            return false
        end
    end

end

1 个答案:

答案 0 :(得分:1)

  

我不确定如何让Sinatra停止为birthdate字段提供该错误并在页面上显示错误消息

如果您想要无效输入的错误页面,请使用error handlerhalt

if params["birthdate"].nil? || params["birthdate"].empty?
  halt 404, erb(:my_custom_error_page_for_invalid_stuff)
end

error InvalidBirthdate do
  halt 404, erb(:my_custom_error_page_for_invalid_stuff)
end

if params["birthdate"].nil? || params["birthdate"].empty?
  raise InvalidBirthdate, "Birthdate was empty!"
end

如果你使用错误处理程序,你可以访问env['sinatra.error'].message,你可以在模板中使用它。

编辑:

  

我实际上是在尝试将错误消息显示在同一页面上而不创建包含错误消息的其他页面

好的,有几种方法可以做到这一点。首先要说的是,响应永远不应该发送到服务器,你可以使用HTML5 validations,也可以覆盖javascript验证。这并不意味着您也不应该检查服务器,有客户端不使用javascript,恶意客户端等。

因此,一种方法是在模板中使用flash或条件。这是一个简单的flash消息(使用flash库会更好):

helpers do
  def flash warning
    %Q!<span class="flash warning">#{warning}</span>!
  end
end

# in the route
if params["birthdate"].nil? || params["birthdate"].empty?
  halt 404, haml(:_form, :locals => {warning: "Fill in your birthdate!"})
end

#_form.haml   # I never use ERB and can't remember conditional syntax for it, sorry
- if warning
  = flash warning 
-# rest of form follows… try to put in their initial responses too :)

或者您可以使用AJAX发送表单,不要将它们从页面中删除,或者您可以将实际表单部分放在一个部分中,并将其包括在_form.erb_my_form_error_page.erb中,并以任何方式提供服务一套。