ayounis90 ayounis90 - 1 year ago 108
Ruby Question

Rails undefined method 'model_name' for nil:nilClass with nested attributes

I have in my orders/edit.html.erb a form that begins like this:

<%= simple_form_for [@reservation, @order] do |f| %>

Orders Controller:

def edit
@reservation = Reservation.find_by_id(params[:reservation_id])
@order = Order.find_by_id(params[:id])




resources :reservations do
resources :orders

If my path resembles something like
I end up getting an error from Rails saying
NoMethodError in Orders#edit
undefined method 'model_name' for nil:NilClass

When I create a new order the form works perfectly fine so not sure why i'm getting an error all of a sudden, can someone help me with this issue?

Answer Source

Current implementation is prone to failure when the URL supplied either a reservation ID or an order ID that is not valid. Two ways to handle this:

First, let Rails do it for you:

def edit
  @reservation = Reservation.find(params[:reservation_id])
  @order       = Order.find(params[:id])

This will raise an ActiveRecord::RecordNotFound error, which, in production, should lead users to your 404 page.

If you'd prefer to keep find_by_id and handle this manually, or to rescue from this error in a different way, you can do:

def edit
  @reservation = Reservation.find_by_id(params[:reservation_id])
  @order       = Order.find_by_id(params[:id])

  if @reservation.nil? || @order.nil?
    raise ActiveRecord::RecordNotFound.new # Or, do something else

That would yield the same result as above ... just more code.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download