Mukul
Mukul

Reputation: 355

What's the solution for nil.update_attributes in ruby?

I'm unable to crack this error. Can't figure out why @customer is being assigned to value nil.

"You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.update_attributes"

Here is a snippet of the code :

def cedit
  @title = "Edit Customer Information"
  @customer = Customer.find(params[:id])
  if request.post? and params[:customer]
    attribute = params[:attribute]
    case attribute
      when "fname"
        try_to_update @customer, attribute
      when "email"
        try_to_update @customer, attribute
      when "add"
        try_to_update @customer, attribute
    end
  end
end


private
  def try_to_update(customer, attribute)
    if customer.update_attributes(params[:customer])
      flash[:notice] = "Customer's details updated."
      redirect_to :action => "record", :controller => "c2"  
    end
  end

Upvotes: 0

Views: 455

Answers (1)

Maran
Maran

Reputation: 2736

First of all your code looks very none-rails like and breaks a couple of rails best practices. I would strongly recommend you read the official Rails guide and try to see if you can refactor some of your code.

I have too little information on what you are trying to do in the grand scale of things so I can't give you a full fledged answer. But you probably want to do something along these lines.

class CustomersController < ApplicationController
  def update
    @customer = Customer.find(params[:id])
    if @customer.update_attributes(params[:customer])
      flash[:notice] = "Customer updated"
    end
    redirect_to customer_path(@customer)
  end
end

The view could look something like this:

<%= form_for(:customer) do |f| %>
  <%= f.text_field :fname %>
  <%= f.text_field :email %>
  <%= f.text_field :add %>
  <%= f.submit_tag "Update" %>
<% end %>

Good luck!

Upvotes: 1

Related Questions