【问题标题】:user validations & displaying an error message in a view用户验证并在视图中显示错误消息
【发布时间】:2015-09-15 09:06:57
【问题描述】:

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

这适用于用户应该输入名字、姓氏和出生日期的表单。 "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

假设总是有输入,因此如果您将生日字段留空并且永远不会显示错误消息,Sinatra 会说“ArgumentError:无效日期”。我不确定如何让 Sinatra 停止为生日字段提供该错误并在页面上显示错误消息,但如果我输入生日并将姓名字段留空,则不会显示错误消息。

这是我的 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

【问题讨论】:

    标签: ruby validation activerecord sinatra


    【解决方案1】:

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

    如果您想要无效输入的错误页面,请使用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 中,并提供适合的任何一个。

    【讨论】:

    • 有趣...我实际上是在尝试让错误消息显示在同一页面上,但没有创建另一个带有错误消息的页面。这类似于如果您在页面上输入错误的用户名,同一页面会在用户名文本字段上方显示“用户名不正确”之类的消息,并且不会将您重定向到另一个页面。
    • 到目前为止您发布的所有内容听起来都很棒。但是,这是针对 Ruby 类的,他们希望我们让错误消息在没有任何其他东西的情况下工作(仅 Sinatra 和 Ruby)。我确实同意引入 Javascript 或其他东西可能会更容易。我在上面发布的代码就像为课程发布的解决方案,我不确定为什么我的代码不起作用,因为它在我看来与发布的内容相同。班上没有其他人提到有任何问题,所以这个周末我要坐下来,弄清楚我与 Sinatra 有什么问题。不过谢谢!
    • @user4992261 那么,最简​​单的事情就是使用if !params.empty?(:birthdate) &amp;&amp; params[:birthdate].include?("-"),这样它就不会溜走。 blank? 会比 empty? 好,但一步一步:)
    • 我认为问题出在 if/else 语句上。我尝试了你的新 if 子句,浏览器现在给了我“ArgumentError:错误数量的参数(1 代表 0)”。
    • 我也试过 if !params[:birthdate].empty? && params[:birthdate].include?("-") 但这只是给出了我遇到的原始“ArgumentError: invalid date”错误。
    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多