在使rails关联无效之前存储值

时间:2011-10-28 22:08:38

标签: ruby-on-rails ruby

好的,我是ruby和rails的新手,我似乎无法得到我认为简单的工作。基本上我的代码是删除对关联的引用(零)。

我想获取模型的名称成员(Team.name),并在删除flash消息的关联之前将其保存到(team_name)。

这是控制器动作和模型:

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

我收到的错误:

NoMethodError in UsersController#remove_resource

undefined method `name' for nil:NilClass

追踪:

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

现在只有在我检索

时才会出现错误
@user.team.name

如果我删除了这个以及对变量team_name的引用,那么一切正常。 谢谢!

1 个答案:

答案 0 :(得分:1)

您收到此错误,因为您不再关联@user.team。只有nil没有模型特定方法name。因此,在执行可能不存在的关联对象的方法之前,您需要验证是否是一个关联的团队。

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