开发者

RoR : You have a nil object you did not expect

开发者 https://www.devze.com 2023-03-21 06:55 出处:网络
Been Facing this issue,I Have as my view <%= form_for(:pin, :url => {:action =>\"fees\"}) do |f| %>

Been Facing this issue,I Have as my view

 <%= form_for(:pin, :url => {:action =>"fees"}) do |f| %>
 <%= f.text_field :pin_no %>
 <%= f.submit "Check Pin" , :class => "new_button round" %>
 <% end %>

and in my controller i have

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

in my model, i have a check_pin method defined thus

def check_pin(pin_to_check)  
  pin = find_by_pin_no(pin_to_check)
   if pin.nil?
     nil
   else
     pin
    end
  end

开发者_如何学Cand i always have this error

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.[]

what am i missing here please?


You get params[:pin][:pin_no] only when you post the form so it is giving error nil.[] so add request.post? to check it only when form is 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


What if you try to simplify it a bit and scrap the check pin method and just do this:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消