0

I am trying to check that an address isn't being used before I delete it. My code is as follows:

def destroy
        @address = current_user.addresses.find_by_id(params[:id])
        redirect_to user_addresses_path(current_user) if @address.nil?

        if Organisation.find_by_address_id(params[:id]).count == 0 && Event.find_by_address_id(params[:id]).count == 0
            @address.destroy
            redirect_to user_addresses_path(current_user)
        else
            flash[:error] = "Cannot delete address because it is being used"
            redirect_to user_addresses_path(current_user)
        end
    end

however, this gives me an error:

undefined method `count' for nil:NilClass

What am I doing wrong?

3
  • address_id is an index on both tables, if that is of any relevance. Commented May 11, 2012 at 21:27
  • Please only tag your questions with language tags please. This is so we can keep tagspam on Stack Overflow to a minimum. Thanks. Commented May 11, 2012 at 21:34
  • Sorry, I thought they were relevant to my query. Lesson learnt. Commented May 12, 2012 at 6:38

1 Answer 1

2

Organisation.find_by_address_id(params[:id]) will return a single object, or nil if one without that address_id does not exist.

Perhaps you meant Organisation.find_all_by_address_id(params[:id]).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.