面对这个问题,我有我的看法
<%= form_for(:pin, :url => {:action =>"fees"}) do |f| %>
<%= f.text_field :pin_no %>
<%= f.submit "Check Pin" , :class => "new_button round" %>
<% end %>
在我的控制器中我有
def fees
@title = "Pay Fees"
pin = Pin.check_pin(params[:pin][:pin_no])
if pin.nil?
flash.now[:error] = "Pin is not Avaliable"
render 'fees'
else
flash.now[:success] = "Pin Avaliable"
end
end
在我的模型中,我有一个如此定义的check_pin方法
def check_pin(pin_to_check)
pin = find_by_pin_no(pin_to_check)
if pin.nil?
nil
else
pin
end
end
我总是有这个错误
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]
我在这里想念的是什么?
答案 0 :(得分:2)
只有在您发布表单时才会收到params[:pin][:pin_no]
,因此错误为nil.[]
,因此只有在表单发布时才添加request.post?
进行检查
def fees
@title = "Pay Fees"
if request.post?
pin = Pin.check_pin(params[:pin][:pin_no])
if pin.nil?
flash.now[:error] = "Pin is not Avaliable"
render 'fees'
else
flash.now[:success] = "Pin Avaliable"
end
end
end
答案 1 :(得分:0)
如果您尝试简化它并废弃检查引脚方法并执行此操作,那该怎么办:
def fees
@title = "Pay Fees"
if p = Pin.find_by_pin_no params[:pin][:pin_no]
flash.now[:success] = "Pin: #{p} is Avaliable"
else
flash.now[:error] = "Pin is not Avaliable"
render 'fees'
end
end