Gregor
Gregor

Reputation: 133

storing a value before nullifying a rails association

Ok, im new to ruby and rails, I cant seem to get which I would assume to be simple working. Basically my code is to remove a reference to an association (nil it).

I want to get the name member (Team.name) of the model and save it to (team_name) before removing the association for the flash message.

Here is the controller action and Models:

def remove_resource
    ...
    @user = User.find(params[:user_id])
    team_name = @user.team.name
    @user.team = nil
    if @user.save
      flash[:notice] = "<a href=\"#{user_path(@user)}\">#{@user.name}</a> was removed from "+team_name+". They are no longer on a team."
      ...
    end
    ...
end

class Team < ActiveRecord::Base

    has_many   :user, :class_name => "User", :foreign_key => "user_id", 
                       :order => "team_start"

    ...

    def ==(another_team)
        if self.name != another_team.name then 
          return false
        end

        if self.location != another_team.location then
          return false
        end
        ...
        true
    end

    ...

end

class User < ActiveRecord::Base

    belongs_to :team,  :class_name => "Team", 
                       :foreign_key => "team_id"

    ...
end

The Errors I am receiving:

NoMethodError in UsersController#remove_resource

undefined method `name' for nil:NilClass

The trace:

app/models/user.rb:50:in `=='
app/controllers/teams_controller.rb:50:in `remove_resource'

Now the error only occurs when I retrieve the

@user.team.name

If I delete this and the reference to the variable team_name, all works fine. Thanks!

Upvotes: 0

Views: 248

Answers (1)

davidb
davidb

Reputation: 8954

You get this error because you dont have the @user.team associated anymore. There is only a nil which doesnt have the Model specific method name. So you need to validate if threre is a team associated or not before executing methods of a associated object that may not be there.

def remove_resource
    ...
    @user = User.find(params[:user_id])
    if @user.team.nil? # Check if theres a associated object
        #do sth. when theres no team to remove
    else
        team_name = @user.team.name
        @user.team = nil
        if @user.save
        flash[:notice] = "<a href=\"#{user_path(@user)}\">#{@user.name}</a> was removed from "+team_name+". They are no longer on a team."
      ...
    end
    ...
end

Upvotes: 1

Related Questions