【发布时间】:2015-05-21 02:23:47
【问题描述】:
我有一个简单的应用程序,它会要求用户输入他们的起点和终点地址,一旦他们这样做,他们就可以点击提交并获得接下来 3 辆公共汽车/火车到目的地的列表。但是,我无法处理用户根本没有输入任何内容并点击提交按钮的情况。
这是简单表单的代码
<%= form_tag("/welcome/index", method: "post") do %>
<div class ="input-group">
<label>Current Location</label>
<%= text_field_tag("address", params['address'], :class => 'form-control') %>
</div><br/>
<div class ="input-group">
<label>Destination Location</label>
<%= text_field_tag("destaddress", params['destaddress'], :class => 'form-control') %>
</div>
<p>
<br/>
<%= submit_tag "", :value => "Find Buses", :class => "btn btn-default" %> </p>
<% end %>
这是我的控制器,我在其中捕获用户的输入并运行我的逻辑以提供总线列表。
class WelcomeController < ApplicationController
# displays the form, so change the name of the form you have now to new.html.erb
def new
end
# the form will pass to this action to perform logic on longitude and latitude
def create
curAddress = params[:address]
destAddress = params[:destaddress]
#2 close stops to current location
@currentList = Stop.by_distance(:origin => curAddress).limit(2)
if @currentList.length == 0
flash[:error] = "Somethig is wrong"
end
#2 closest stops to destination location
@destList = Stop.by_distance(:origin => destAddress).limit(2)
@startIds = Array.new
2.times do |i|
@startIds.push(@currentList[i].id)
end
@endIds = Array.new
2.times do |i|
@endIds.push(@destList[i].id)
end
@currentStop = Stop.closest(:origin => curAddress)
@destinationStop = Stop.closest(:origin => destAddress)
@timeNow = Time.now.in_time_zone("EST") + 1.hour
@finalTime = @timeNow.strftime("%H:%M:%S")
startStopId = @currentStop.first.id
endStopId = @destinationStop.first.id
#update it based on succeed
@cStop = Stop.find(startStopId)
@dStop = Stop.find(endStopId)
testMethod(startStopId,endStopId)
render :index
end
我所做的基本上是接受用户的输入,然后尝试使用一个名为 Geokit 的 gem 来查找用户给定地址的两个最近的站点,并将他们的 ID 存储在@currentList and @destList
所以很明显,如果用户没有给出任何输入,那么这两个列表应该是空的。所以使用这个逻辑我尝试了这个
if @currentList.length == 0
flash[:error] = "Somethig is wrong"
end
但是我无法处理用户没有输入的情况。所以我想知道如何处理它?理想情况下,我想在表单上显示一条消息,说“没有输入输入”,这样用户将重试输入一些输入,然后点击提交。我对 ruby on rails 非常陌生,例如我知道在 java 中我可以抛出异常或其他东西。
【问题讨论】:
标签: ruby-on-rails ruby