Ashley Bye
Ashley Bye

Reputation: 1750

Rails undefined method count

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?

Upvotes: 0

Views: 4074

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107728

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

Upvotes: 2

Related Questions